blob: c54a006d26a765bd30ccdffc47a811361c4d47b0 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
330} // unnamed namespace
331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
429 ThisDeclInfo);
430 return CFC;
431
432}
433
Richard Smithb39b9d52013-05-21 05:24:00 +0000434comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000437}
438
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000439comments::FullComment *ASTContext::getCommentForDecl(
440 const Decl *D,
441 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000442 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000443 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449
450 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 return CFC;
455 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000456 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 }
458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (!RC) {
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000464 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000470 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000476 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000478 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000479 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000480 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000484 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000485 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
497 }
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000500 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000501 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510 continue;
511
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000519 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000520 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000521 if (Ty.isNull())
522 continue;
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
525 continue;
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
528 }
529 }
530 }
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000532 }
533
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000542 ParsedComments[Canonical] = FC;
543 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000544}
545
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000546void
547ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000552
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
557 P != PEnd; ++P) {
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559 ID.AddInteger(0);
560 ID.AddBoolean(TTP->isParameterPack());
561 continue;
562 }
563
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000566 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000568 if (NTTP->isExpandedParameterPack()) {
569 ID.AddBoolean(true);
570 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000575 } else
576 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 continue;
578 }
579
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581 ID.AddInteger(2);
582 Profile(ID, TTP);
583 }
584}
585
586TemplateTemplateParmDecl *
587ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000588 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000592 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595 if (Canonical)
596 return Canonical->getParam();
597
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
604 P != PEnd; ++P) {
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000608 SourceLocation(),
609 SourceLocation(),
610 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000611 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625 }
626
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000628 SourceLocation(),
629 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000630 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000631 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 T,
633 TInfo,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
662 CanonParams.data(),
663 CanonParams.size(),
664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000687 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000688 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000689 return CreateMicrosoftCXXABI(*this);
690 }
David Blaikie8a40f702012-01-17 06:56:22 +0000691 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000692}
693
Douglas Gregore8bbc122011-09-02 00:18:52 +0000694static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000695 const LangOptions &LOpts) {
696 if (LOpts.FakeAddressSpaceMap) {
697 // The fake address space map must have a distinct entry for each
698 // language-specific address space.
699 static const unsigned FakeAddrSpaceMap[] = {
700 1, // opencl_global
701 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000702 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000703 4, // opencl_generic
704 5, // cuda_device
705 6, // cuda_constant
706 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 }
712}
713
David Tweed31d09b02013-09-13 12:04:22 +0000714static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
715 const LangOptions &LangOpts) {
716 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000717 case LangOptions::ASMM_Target:
718 return TI.useAddressSpaceMapMangling();
719 case LangOptions::ASMM_On:
720 return true;
721 case LangOptions::ASMM_Off:
722 return false;
723 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000724 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000725}
726
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000727ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000728 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000729 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000730 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
731 DependentTemplateSpecializationTypes(this_()),
732 SubstTemplateTemplateParmPacks(this_()),
733 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
734 UInt128Decl(nullptr), Float128StubDecl(nullptr),
735 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
736 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
739 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
740 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000741 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
742 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000743 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000744 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
745 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
746 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
747 Comments(SM), CommentsLoaded(false),
748 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000749 TUDecl = TranslationUnitDecl::Create(*this);
750}
751
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000752ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000753 ReleaseParentMapEntries();
754
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000755 // Release the DenseMaps associated with DeclContext objects.
756 // FIXME: Is this the ideal solution?
757 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000758
Manuel Klimeka7328992013-06-03 13:51:33 +0000759 // Call all of the deallocation functions on all of their targets.
760 for (DeallocationMap::const_iterator I = Deallocations.begin(),
761 E = Deallocations.end(); I != E; ++I)
762 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763 (I->first)((I->second)[J]);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
Reid Kleckner588c9372014-02-19 23:44:52 +0000786 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000787}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000788
Manuel Klimek95403e62014-05-21 13:28:59 +0000789void ASTContext::ReleaseParentMapEntries() {
790 if (!AllParents) return;
791 for (const auto &Entry : *AllParents) {
792 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
793 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
794 } else {
795 assert(Entry.second.is<ParentVector *>());
796 delete Entry.second.get<ParentVector *>();
797 }
798 }
799}
800
Douglas Gregor1a809332010-05-23 18:26:36 +0000801void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000802 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000803}
804
Mike Stump11289f42009-09-09 15:08:12 +0000805void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000806ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
807 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000808}
809
Chris Lattner4eb445d2007-01-26 01:27:23 +0000810void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000811 llvm::errs() << "\n*** AST Context Stats:\n";
812 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000813
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000815#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000816#define ABSTRACT_TYPE(Name, Parent)
817#include "clang/AST/TypeNodes.def"
818 0 // Extra
819 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000820
Chris Lattner4eb445d2007-01-26 01:27:23 +0000821 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
822 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000823 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000824 }
825
Douglas Gregora30d0462009-05-26 14:40:08 +0000826 unsigned Idx = 0;
827 unsigned TotalBytes = 0;
828#define TYPE(Name, Parent) \
829 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000830 llvm::errs() << " " << counts[Idx] << " " << #Name \
831 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 TotalBytes += counts[Idx] * sizeof(Name##Type); \
833 ++Idx;
834#define ABSTRACT_TYPE(Name, Parent)
835#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chandler Carruth3c147a72011-07-04 05:32:14 +0000837 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
838
Douglas Gregor7454c562010-07-02 20:37:36 +0000839 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000840 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
841 << NumImplicitDefaultConstructors
842 << " implicit default constructors created\n";
843 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
844 << NumImplicitCopyConstructors
845 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000846 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000847 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
848 << NumImplicitMoveConstructors
849 << " implicit move constructors created\n";
850 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
851 << NumImplicitCopyAssignmentOperators
852 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000853 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000854 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
855 << NumImplicitMoveAssignmentOperators
856 << " implicit move assignment operators created\n";
857 llvm::errs() << NumImplicitDestructorsDeclared << "/"
858 << NumImplicitDestructors
859 << " implicit destructors created\n";
860
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000861 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000862 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000863 ExternalSource->PrintStats();
864 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000865
Douglas Gregor5b11d492010-07-25 17:53:33 +0000866 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000867}
868
Richard Smithf19e1272015-03-07 00:04:49 +0000869ExternCContextDecl *ASTContext::getExternCContextDecl() const {
870 if (!ExternCContext)
871 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
872
873 return ExternCContext;
874}
875
Alp Toker2dea15b2013-12-17 01:22:38 +0000876RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
877 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000878 SourceLocation Loc;
879 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000880 if (getLangOpts().CPlusPlus)
881 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
882 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000883 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000884 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
885 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000886 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000887 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
888 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000889 return NewDecl;
890}
891
892TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
893 StringRef Name) const {
894 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
895 TypedefDecl *NewDecl = TypedefDecl::Create(
896 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
897 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
898 NewDecl->setImplicit();
899 return NewDecl;
900}
901
Douglas Gregor801c99d2011-08-12 06:49:56 +0000902TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000903 if (!Int128Decl)
904 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000905 return Int128Decl;
906}
907
908TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000909 if (!UInt128Decl)
910 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000911 return UInt128Decl;
912}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000913
Nico Webere1687c52013-06-20 21:44:55 +0000914TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000915 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000916 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000917 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000918
Nico Webere1687c52013-06-20 21:44:55 +0000919 return Float128StubDecl;
920}
921
John McCall48f2d582009-10-23 23:03:21 +0000922void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000923 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000924 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000925 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000926}
927
Douglas Gregore8bbc122011-09-02 00:18:52 +0000928void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
929 assert((!this->Target || this->Target == &Target) &&
930 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000931 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000932
Douglas Gregore8bbc122011-09-02 00:18:52 +0000933 this->Target = &Target;
934
935 ABI.reset(createCXXABI(Target));
936 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000937 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000938
Chris Lattner970e54e2006-11-12 00:37:36 +0000939 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000940 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner970e54e2006-11-12 00:37:36 +0000942 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000943 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000944 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000945 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000946 InitBuiltinType(CharTy, BuiltinType::Char_S);
947 else
948 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000949 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000950 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
951 InitBuiltinType(ShortTy, BuiltinType::Short);
952 InitBuiltinType(IntTy, BuiltinType::Int);
953 InitBuiltinType(LongTy, BuiltinType::Long);
954 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000955
Chris Lattner970e54e2006-11-12 00:37:36 +0000956 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000957 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
958 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
959 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
960 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
961 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000962
Chris Lattner970e54e2006-11-12 00:37:36 +0000963 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000964 InitBuiltinType(FloatTy, BuiltinType::Float);
965 InitBuiltinType(DoubleTy, BuiltinType::Double);
966 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000967
Chris Lattnerf122cef2009-04-30 02:43:43 +0000968 // GNU extension, 128-bit integers.
969 InitBuiltinType(Int128Ty, BuiltinType::Int128);
970 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
971
Hans Wennborg0d81e012013-05-10 10:08:40 +0000972 // C++ 3.9.1p5
973 if (TargetInfo::isTypeSigned(Target.getWCharType()))
974 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
975 else // -fshort-wchar makes wchar_t be unsigned.
976 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
977 if (LangOpts.CPlusPlus && LangOpts.WChar)
978 WideCharTy = WCharTy;
979 else {
980 // C99 (or C++ using -fno-wchar).
981 WideCharTy = getFromTargetType(Target.getWCharType());
982 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000983
James Molloy36365542012-05-04 10:55:22 +0000984 WIntTy = getFromTargetType(Target.getWIntType());
985
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000986 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
987 InitBuiltinType(Char16Ty, BuiltinType::Char16);
988 else // C99
989 Char16Ty = getFromTargetType(Target.getChar16Type());
990
991 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
992 InitBuiltinType(Char32Ty, BuiltinType::Char32);
993 else // C99
994 Char32Ty = getFromTargetType(Target.getChar32Type());
995
Douglas Gregor4619e432008-12-05 23:32:09 +0000996 // Placeholder type for type-dependent expressions whose type is
997 // completely unknown. No code should ever check a type against
998 // DependentTy and users should never see it; however, it is here to
999 // help diagnose failures to properly check for type-dependent
1000 // expressions.
1001 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001002
John McCall36e7fe32010-10-12 00:20:44 +00001003 // Placeholder type for functions.
1004 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1005
John McCall0009fcc2011-04-26 20:42:42 +00001006 // Placeholder type for bound members.
1007 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1008
John McCall526ab472011-10-25 17:37:35 +00001009 // Placeholder type for pseudo-objects.
1010 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1011
John McCall31996342011-04-07 08:22:57 +00001012 // "any" type; useful for debugger-like clients.
1013 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1014
John McCall8a6b59a2011-10-17 18:09:15 +00001015 // Placeholder type for unbridged ARC casts.
1016 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1017
Eli Friedman34866c72012-08-31 00:14:07 +00001018 // Placeholder type for builtin functions.
1019 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1020
Chris Lattner970e54e2006-11-12 00:37:36 +00001021 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001022 FloatComplexTy = getComplexType(FloatTy);
1023 DoubleComplexTy = getComplexType(DoubleTy);
1024 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001026 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001027 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1028 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001029 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001030
1031 if (LangOpts.OpenCL) {
1032 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1033 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1034 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1035 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1036 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1037 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001038
Guy Benyei61054192013-02-07 10:55:47 +00001039 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001040 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001041 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001042
1043 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001044 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1045 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001046
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001047 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001048
1049 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001050
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001051 // void * type
1052 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001053
1054 // nullptr type (C++0x 2.14.7)
1055 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001056
1057 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1058 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001059
1060 // Builtin type used to help define __builtin_va_list.
1061 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001062}
1063
David Blaikie9c902b52011-09-25 23:23:43 +00001064DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001065 return SourceMgr.getDiagnostics();
1066}
1067
Douglas Gregor561eceb2010-08-30 16:49:28 +00001068AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1069 AttrVec *&Result = DeclAttrs[D];
1070 if (!Result) {
1071 void *Mem = Allocate(sizeof(AttrVec));
1072 Result = new (Mem) AttrVec;
1073 }
1074
1075 return *Result;
1076}
1077
1078/// \brief Erase the attributes corresponding to the given declaration.
1079void ASTContext::eraseDeclAttrs(const Decl *D) {
1080 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1081 if (Pos != DeclAttrs.end()) {
1082 Pos->second->~AttrVec();
1083 DeclAttrs.erase(Pos);
1084 }
1085}
1086
Larisse Voufo39a1e502013-08-06 01:03:05 +00001087// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001088MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001089ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001090 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001091 return getTemplateOrSpecializationInfo(Var)
1092 .dyn_cast<MemberSpecializationInfo *>();
1093}
1094
1095ASTContext::TemplateOrSpecializationInfo
1096ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1097 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1098 TemplateOrInstantiation.find(Var);
1099 if (Pos == TemplateOrInstantiation.end())
1100 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001101
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001102 return Pos->second;
1103}
1104
Mike Stump11289f42009-09-09 15:08:12 +00001105void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001106ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001107 TemplateSpecializationKind TSK,
1108 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001109 assert(Inst->isStaticDataMember() && "Not a static data member");
1110 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001111 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1112 Tmpl, TSK, PointOfInstantiation));
1113}
1114
1115void
1116ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1117 TemplateOrSpecializationInfo TSI) {
1118 assert(!TemplateOrInstantiation[Inst] &&
1119 "Already noted what the variable was instantiated from");
1120 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001121}
1122
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001123FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1124 const FunctionDecl *FD){
1125 assert(FD && "Specialization is 0");
1126 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001127 = ClassScopeSpecializationPattern.find(FD);
1128 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001129 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001130
1131 return Pos->second;
1132}
1133
1134void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1135 FunctionDecl *Pattern) {
1136 assert(FD && "Specialization is 0");
1137 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001138 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001139}
1140
John McCalle61f2ba2009-11-18 02:36:19 +00001141NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001142ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001143 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001144 = InstantiatedFromUsingDecl.find(UUD);
1145 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001146 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001147
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001148 return Pos->second;
1149}
1150
1151void
John McCallb96ec562009-12-04 22:46:56 +00001152ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1153 assert((isa<UsingDecl>(Pattern) ||
1154 isa<UnresolvedUsingValueDecl>(Pattern) ||
1155 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1156 "pattern decl is not a using decl");
1157 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1158 InstantiatedFromUsingDecl[Inst] = Pattern;
1159}
1160
1161UsingShadowDecl *
1162ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1163 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1164 = InstantiatedFromUsingShadowDecl.find(Inst);
1165 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001166 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001167
1168 return Pos->second;
1169}
1170
1171void
1172ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1173 UsingShadowDecl *Pattern) {
1174 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1175 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001176}
1177
Anders Carlsson5da84842009-09-01 04:26:58 +00001178FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1179 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1180 = InstantiatedFromUnnamedFieldDecl.find(Field);
1181 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001182 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001183
Anders Carlsson5da84842009-09-01 04:26:58 +00001184 return Pos->second;
1185}
1186
1187void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1188 FieldDecl *Tmpl) {
1189 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1190 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1191 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1192 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001193
Anders Carlsson5da84842009-09-01 04:26:58 +00001194 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1195}
1196
Douglas Gregor832940b2010-03-02 23:58:15 +00001197ASTContext::overridden_cxx_method_iterator
1198ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001200 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001201 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001202 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001203
1204 return Pos->second.begin();
1205}
1206
1207ASTContext::overridden_cxx_method_iterator
1208ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1209 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001210 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001211 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001212 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001213
1214 return Pos->second.end();
1215}
1216
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001217unsigned
1218ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1219 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001220 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001221 if (Pos == OverriddenMethods.end())
1222 return 0;
1223
1224 return Pos->second.size();
1225}
1226
Douglas Gregor832940b2010-03-02 23:58:15 +00001227void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1228 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001229 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001230 OverriddenMethods[Method].push_back(Overridden);
1231}
1232
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001233void ASTContext::getOverriddenMethods(
1234 const NamedDecl *D,
1235 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001236 assert(D);
1237
1238 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001239 Overridden.append(overridden_methods_begin(CXXMethod),
1240 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001241 return;
1242 }
1243
1244 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1245 if (!Method)
1246 return;
1247
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001248 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1249 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001250 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001251}
1252
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001253void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1254 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1255 assert(!Import->isFromASTFile() && "Non-local import declaration");
1256 if (!FirstLocalImport) {
1257 FirstLocalImport = Import;
1258 LastLocalImport = Import;
1259 return;
1260 }
1261
1262 LastLocalImport->NextLocalImport = Import;
1263 LastLocalImport = Import;
1264}
1265
Chris Lattner53cfe802007-07-18 17:52:12 +00001266//===----------------------------------------------------------------------===//
1267// Type Sizing and Analysis
1268//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001269
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001270/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1271/// scalar floating point type.
1272const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001273 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001274 assert(BT && "Not a floating point type!");
1275 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001276 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001277 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001278 case BuiltinType::Float: return Target->getFloatFormat();
1279 case BuiltinType::Double: return Target->getDoubleFormat();
1280 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001281 }
1282}
1283
Rafael Espindola71eccb32013-08-08 19:53:46 +00001284CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001285 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001286
John McCall94268702010-10-08 18:24:19 +00001287 bool UseAlignAttrOnly = false;
1288 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1289 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001290
John McCall94268702010-10-08 18:24:19 +00001291 // __attribute__((aligned)) can increase or decrease alignment
1292 // *except* on a struct or struct member, where it only increases
1293 // alignment unless 'packed' is also specified.
1294 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001295 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001296 // ignore that possibility; Sema should diagnose it.
1297 if (isa<FieldDecl>(D)) {
1298 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1299 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1300 } else {
1301 UseAlignAttrOnly = true;
1302 }
1303 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001304 else if (isa<FieldDecl>(D))
1305 UseAlignAttrOnly =
1306 D->hasAttr<PackedAttr>() ||
1307 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001308
John McCall4e819612011-01-20 07:57:12 +00001309 // If we're using the align attribute only, just ignore everything
1310 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001311 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001312 // do nothing
1313
John McCall94268702010-10-08 18:24:19 +00001314 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001315 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001316 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001317 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001318 T = RT->getPointeeType();
1319 else
1320 T = getPointerType(RT->getPointeeType());
1321 }
Richard Smithf6d70302014-06-10 23:34:28 +00001322 QualType BaseT = getBaseElementType(T);
1323 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001324 // Adjust alignments of declarations with array type by the
1325 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001326 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001327 unsigned MinWidth = Target->getLargeArrayMinWidth();
1328 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001329 if (isa<VariableArrayType>(arrayType))
1330 Align = std::max(Align, Target->getLargeArrayAlign());
1331 else if (isa<ConstantArrayType>(arrayType) &&
1332 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1333 Align = std::max(Align, Target->getLargeArrayAlign());
1334 }
John McCall33ddac02011-01-19 10:06:00 +00001335 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001336 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001337 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001338 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001339 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1340 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001341 }
John McCall4e819612011-01-20 07:57:12 +00001342
1343 // Fields can be subject to extra alignment constraints, like if
1344 // the field is packed, the struct is packed, or the struct has a
1345 // a max-field-alignment constraint (#pragma pack). So calculate
1346 // the actual alignment of the field within the struct, and then
1347 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001348 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1349 const RecordDecl *Parent = Field->getParent();
1350 // We can only produce a sensible answer if the record is valid.
1351 if (!Parent->isInvalidDecl()) {
1352 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001353
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001354 // Start with the record's overall alignment.
1355 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001356
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001357 // Use the GCD of that and the offset within the record.
1358 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1359 if (Offset > 0) {
1360 // Alignment is always a power of 2, so the GCD will be a power of 2,
1361 // which means we get to do this crazy thing instead of Euclid's.
1362 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1363 if (LowBitOfOffset < FieldAlign)
1364 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1365 }
1366
1367 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001368 }
Charles Davis3fc51072010-02-23 04:52:00 +00001369 }
Chris Lattner68061312009-01-24 21:53:27 +00001370 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001371
Ken Dyckcc56c542011-01-15 18:38:59 +00001372 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001373}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001374
John McCallf1249922012-08-21 04:10:00 +00001375// getTypeInfoDataSizeInChars - Return the size of a type, in
1376// chars. If the type is a record, its data size is returned. This is
1377// the size of the memcpy that's performed when assigning this type
1378// using a trivial copy/move assignment operator.
1379std::pair<CharUnits, CharUnits>
1380ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1381 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1382
1383 // In C++, objects can sometimes be allocated into the tail padding
1384 // of a base-class subobject. We decide whether that's possible
1385 // during class layout, so here we can just trust the layout results.
1386 if (getLangOpts().CPlusPlus) {
1387 if (const RecordType *RT = T->getAs<RecordType>()) {
1388 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1389 sizeAndAlign.first = layout.getDataSize();
1390 }
1391 }
1392
1393 return sizeAndAlign;
1394}
1395
Richard Trieu04d2d942013-05-14 21:59:17 +00001396/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1397/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1398std::pair<CharUnits, CharUnits>
1399static getConstantArrayInfoInChars(const ASTContext &Context,
1400 const ConstantArrayType *CAT) {
1401 std::pair<CharUnits, CharUnits> EltInfo =
1402 Context.getTypeInfoInChars(CAT->getElementType());
1403 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001404 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1405 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001406 "Overflow in array type char size evaluation");
1407 uint64_t Width = EltInfo.first.getQuantity() * Size;
1408 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001409 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1410 Context.getTargetInfo().getPointerWidth(0) == 64)
1411 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001412 return std::make_pair(CharUnits::fromQuantity(Width),
1413 CharUnits::fromQuantity(Align));
1414}
1415
John McCall87fe5d52010-05-20 01:18:31 +00001416std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001417ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001418 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1419 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001420 TypeInfo Info = getTypeInfo(T);
1421 return std::make_pair(toCharUnitsFromBits(Info.Width),
1422 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001423}
1424
1425std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001426ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001427 return getTypeInfoInChars(T.getTypePtr());
1428}
1429
David Majnemer34b57492014-07-30 01:30:47 +00001430bool ASTContext::isAlignmentRequired(const Type *T) const {
1431 return getTypeInfo(T).AlignIsRequired;
1432}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001433
David Majnemer34b57492014-07-30 01:30:47 +00001434bool ASTContext::isAlignmentRequired(QualType T) const {
1435 return isAlignmentRequired(T.getTypePtr());
1436}
1437
1438TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001439 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1440 if (I != MemoizedTypeInfo.end())
1441 return I->second;
1442
1443 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1444 TypeInfo TI = getTypeInfoImpl(T);
1445 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001446 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001447}
1448
1449/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1450/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001451///
1452/// FIXME: Pointers into different addr spaces could have different sizes and
1453/// alignment requirements: getPointerInfo should take an AddrSpace, this
1454/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001455TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1456 uint64_t Width = 0;
1457 unsigned Align = 8;
1458 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001459 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001460#define TYPE(Class, Base)
1461#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001462#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001463#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001464#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1465 case Type::Class: \
1466 assert(!T->isDependentType() && "should not see dependent types here"); \
1467 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001468#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001469 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001470
Chris Lattner355332d2007-07-13 22:27:08 +00001471 case Type::FunctionNoProto:
1472 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001473 // GCC extension: alignof(function) = 32 bits
1474 Width = 0;
1475 Align = 32;
1476 break;
1477
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001478 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001479 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001480 Width = 0;
1481 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1482 break;
1483
Steve Naroff5c131802007-08-30 01:06:46 +00001484 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001485 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001486
David Majnemer34b57492014-07-30 01:30:47 +00001487 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001488 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001489 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001490 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001491 Width = EltInfo.Width * Size;
1492 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001493 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1494 getTargetInfo().getPointerWidth(0) == 64)
1495 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001496 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001497 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001498 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001499 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001500 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001501 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1502 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001503 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001504 // If the alignment is not a power of 2, round up to the next power of 2.
1505 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001506 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001507 Align = llvm::NextPowerOf2(Align);
1508 Width = llvm::RoundUpToAlignment(Width, Align);
1509 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001510 // Adjust the alignment based on the target max.
1511 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1512 if (TargetVectorAlign && TargetVectorAlign < Align)
1513 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001514 break;
1515 }
Chris Lattner647fb222007-07-18 18:26:58 +00001516
Chris Lattner7570e9c2008-03-08 08:52:55 +00001517 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001518 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001519 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001520 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001521 // GCC extension: alignof(void) = 8 bits.
1522 Width = 0;
1523 Align = 8;
1524 break;
1525
Chris Lattner6a4f7452007-12-19 19:23:28 +00001526 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001527 Width = Target->getBoolWidth();
1528 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001530 case BuiltinType::Char_S:
1531 case BuiltinType::Char_U:
1532 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001533 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001534 Width = Target->getCharWidth();
1535 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001536 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001537 case BuiltinType::WChar_S:
1538 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001539 Width = Target->getWCharWidth();
1540 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001541 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001542 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001543 Width = Target->getChar16Width();
1544 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001545 break;
1546 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001547 Width = Target->getChar32Width();
1548 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001549 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001550 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getShortWidth();
1553 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001555 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001556 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001557 Width = Target->getIntWidth();
1558 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001559 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001560 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001561 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001562 Width = Target->getLongWidth();
1563 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001564 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001565 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001566 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001567 Width = Target->getLongLongWidth();
1568 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001569 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001570 case BuiltinType::Int128:
1571 case BuiltinType::UInt128:
1572 Width = 128;
1573 Align = 128; // int128_t is 128-bit aligned on all targets.
1574 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001575 case BuiltinType::Half:
1576 Width = Target->getHalfWidth();
1577 Align = Target->getHalfAlign();
1578 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001579 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001580 Width = Target->getFloatWidth();
1581 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001582 break;
1583 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001584 Width = Target->getDoubleWidth();
1585 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001586 break;
1587 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001588 Width = Target->getLongDoubleWidth();
1589 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001590 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001591 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1593 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001594 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001595 case BuiltinType::ObjCId:
1596 case BuiltinType::ObjCClass:
1597 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001598 Width = Target->getPointerWidth(0);
1599 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001600 break;
Guy Benyei61054192013-02-07 10:55:47 +00001601 case BuiltinType::OCLSampler:
1602 // Samplers are modeled as integers.
1603 Width = Target->getIntWidth();
1604 Align = Target->getIntAlign();
1605 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001606 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001607 case BuiltinType::OCLImage1d:
1608 case BuiltinType::OCLImage1dArray:
1609 case BuiltinType::OCLImage1dBuffer:
1610 case BuiltinType::OCLImage2d:
1611 case BuiltinType::OCLImage2dArray:
1612 case BuiltinType::OCLImage3d:
1613 // Currently these types are pointers to opaque types.
1614 Width = Target->getPointerWidth(0);
1615 Align = Target->getPointerAlign(0);
1616 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001617 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001618 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001619 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001620 Width = Target->getPointerWidth(0);
1621 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001622 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001623 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001624 unsigned AS = getTargetAddressSpace(
1625 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001626 Width = Target->getPointerWidth(AS);
1627 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001628 break;
1629 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001630 case Type::LValueReference:
1631 case Type::RValueReference: {
1632 // alignof and sizeof should never enter this code path here, so we go
1633 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001634 unsigned AS = getTargetAddressSpace(
1635 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001636 Width = Target->getPointerWidth(AS);
1637 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001638 break;
1639 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001640 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001641 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001642 Width = Target->getPointerWidth(AS);
1643 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001644 break;
1645 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001646 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001647 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001648 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001649 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001650 }
Chris Lattner647fb222007-07-18 18:26:58 +00001651 case Type::Complex: {
1652 // Complex types have the same alignment as their elements, but twice the
1653 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001654 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1655 Width = EltInfo.Width * 2;
1656 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001657 break;
1658 }
John McCall8b07ec22010-05-15 11:32:37 +00001659 case Type::ObjCObject:
1660 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001661 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001662 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001663 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001664 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001665 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001666 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001667 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001668 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001669 break;
1670 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001671 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001672 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001673 const TagType *TT = cast<TagType>(T);
1674
1675 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001676 Width = 8;
1677 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001678 break;
1679 }
Mike Stump11289f42009-09-09 15:08:12 +00001680
David Majnemer475b25e2015-01-21 10:54:38 +00001681 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1682 const EnumDecl *ED = ET->getDecl();
1683 TypeInfo Info =
1684 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1685 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1686 Info.Align = AttrAlign;
1687 Info.AlignIsRequired = true;
1688 }
1689 return Info;
1690 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001691
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001692 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001693 const RecordDecl *RD = RT->getDecl();
1694 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001695 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001696 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001697 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001698 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001699 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001700
Chris Lattner63d2b362009-10-22 05:17:15 +00001701 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001702 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1703 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001704
Richard Smith30482bc2011-02-20 03:19:35 +00001705 case Type::Auto: {
1706 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001707 assert(!A->getDeducedType().isNull() &&
1708 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001709 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001710 }
1711
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001712 case Type::Paren:
1713 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1714
Douglas Gregoref462e62009-04-30 17:32:17 +00001715 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001716 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001717 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001718 // If the typedef has an aligned attribute on it, it overrides any computed
1719 // alignment we have. This violates the GCC documentation (which says that
1720 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001721 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001722 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001723 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001724 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001725 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001726 AlignIsRequired = Info.AlignIsRequired;
1727 }
David Majnemer34b57492014-07-30 01:30:47 +00001728 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001729 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001730 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001731
Abramo Bagnara6150c882010-05-11 21:36:43 +00001732 case Type::Elaborated:
1733 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001734
John McCall81904512011-01-06 01:58:22 +00001735 case Type::Attributed:
1736 return getTypeInfo(
1737 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1738
Eli Friedman0dfb8892011-10-06 23:00:33 +00001739 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001740 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001741 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1742 Width = Info.Width;
1743 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001744
1745 // If the size of the type doesn't exceed the platform's max
1746 // atomic promotion width, make the size and alignment more
1747 // favorable to atomic operations:
1748 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1749 // Round the size up to a power of 2.
1750 if (!llvm::isPowerOf2_64(Width))
1751 Width = llvm::NextPowerOf2(Width);
1752
1753 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001754 Align = static_cast<unsigned>(Width);
1755 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001756 }
1757
Douglas Gregoref462e62009-04-30 17:32:17 +00001758 }
Mike Stump11289f42009-09-09 15:08:12 +00001759
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001760 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001761 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001762}
1763
Ken Dyckcc56c542011-01-15 18:38:59 +00001764/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1765CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1766 return CharUnits::fromQuantity(BitSize / getCharWidth());
1767}
1768
Ken Dyckb0fcc592011-02-11 01:54:29 +00001769/// toBits - Convert a size in characters to a size in characters.
1770int64_t ASTContext::toBits(CharUnits CharSize) const {
1771 return CharSize.getQuantity() * getCharWidth();
1772}
1773
Ken Dyck8c89d592009-12-22 14:23:30 +00001774/// getTypeSizeInChars - Return the size of the specified type, in characters.
1775/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001776CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001777 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001778}
Jay Foad39c79802011-01-12 09:06:06 +00001779CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001780 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001781}
1782
Ken Dycka6046ab2010-01-26 17:25:18 +00001783/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001784/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001785CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001786 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001787}
Jay Foad39c79802011-01-12 09:06:06 +00001788CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001789 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001790}
1791
Chris Lattnera3402cd2009-01-27 18:08:34 +00001792/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1793/// type for the current target in bits. This can be different than the ABI
1794/// alignment in cases where it is beneficial for performance to overalign
1795/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001796unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001797 TypeInfo TI = getTypeInfo(T);
1798 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001799
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001800 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1801 return ABIAlign; // Never overalign on XCore.
1802
Eli Friedman7ab09572009-05-25 21:27:19 +00001803 // Double and long long should be naturally aligned if possible.
Richard Smithd7e1fe42014-06-10 23:43:44 +00001804 T = T->getBaseElementTypeUnsafe();
David Majnemer1d4db8f2014-02-24 23:43:27 +00001805 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001806 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001807 if (const EnumType *ET = T->getAs<EnumType>())
1808 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001809 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001810 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1811 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001812 // Don't increase the alignment if an alignment attribute was specified on a
1813 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001814 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001815 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001816
Chris Lattnera3402cd2009-01-27 18:08:34 +00001817 return ABIAlign;
1818}
1819
Ulrich Weigandfa806422013-05-06 16:23:57 +00001820/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1821/// to a global variable of the specified type.
1822unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1823 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1824}
1825
1826/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1827/// should be given to a global variable of the specified type.
1828CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1829 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1830}
1831
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001832/// DeepCollectObjCIvars -
1833/// This routine first collects all declared, but not synthesized, ivars in
1834/// super class and then collects all ivars, including those synthesized for
1835/// current class. This routine is used for implementation of current class
1836/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001837///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001838void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1839 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001840 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001841 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1842 DeepCollectObjCIvars(SuperClass, false, Ivars);
1843 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001844 for (const auto *I : OI->ivars())
1845 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001846 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001847 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001848 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001849 Iv= Iv->getNextIvar())
1850 Ivars.push_back(Iv);
1851 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001852}
1853
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001854/// CollectInheritedProtocols - Collect all protocols in current class and
1855/// those inherited by it.
1856void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001857 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001858 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001859 // We can use protocol_iterator here instead of
1860 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001861 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001862 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001863 for (auto *P : Proto->protocols()) {
1864 Protocols.insert(P->getCanonicalDecl());
1865 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001866 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001867 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001868
1869 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001870 for (const auto *Cat : OI->visible_categories())
1871 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001872
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001873 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1874 while (SD) {
1875 CollectInheritedProtocols(SD, Protocols);
1876 SD = SD->getSuperClass();
1877 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001878 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001879 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001880 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001881 for (const auto *P : Proto->protocols())
1882 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001883 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001884 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001885 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001886 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001887 for (const auto *P : Proto->protocols())
1888 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001889 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001890 }
1891}
1892
Jay Foad39c79802011-01-12 09:06:06 +00001893unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001894 unsigned count = 0;
1895 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001896 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001897 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001898
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001899 // Count ivar defined in this class's implementation. This
1900 // includes synthesized ivars.
1901 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001902 count += ImplDecl->ivar_size();
1903
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001904 return count;
1905}
1906
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001907bool ASTContext::isSentinelNullExpr(const Expr *E) {
1908 if (!E)
1909 return false;
1910
1911 // nullptr_t is always treated as null.
1912 if (E->getType()->isNullPtrType()) return true;
1913
1914 if (E->getType()->isAnyPointerType() &&
1915 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1916 Expr::NPC_ValueDependentIsNull))
1917 return true;
1918
1919 // Unfortunately, __null has type 'int'.
1920 if (isa<GNUNullExpr>(E)) return true;
1921
1922 return false;
1923}
1924
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001925/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1926ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1927 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1928 I = ObjCImpls.find(D);
1929 if (I != ObjCImpls.end())
1930 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001931 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001932}
1933/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1934ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1935 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1936 I = ObjCImpls.find(D);
1937 if (I != ObjCImpls.end())
1938 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001939 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001940}
1941
1942/// \brief Set the implementation of ObjCInterfaceDecl.
1943void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1944 ObjCImplementationDecl *ImplD) {
1945 assert(IFaceD && ImplD && "Passed null params");
1946 ObjCImpls[IFaceD] = ImplD;
1947}
1948/// \brief Set the implementation of ObjCCategoryDecl.
1949void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1950 ObjCCategoryImplDecl *ImplD) {
1951 assert(CatD && ImplD && "Passed null params");
1952 ObjCImpls[CatD] = ImplD;
1953}
1954
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001955const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1956 const NamedDecl *ND) const {
1957 if (const ObjCInterfaceDecl *ID =
1958 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001959 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001960 if (const ObjCCategoryDecl *CD =
1961 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001962 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001963 if (const ObjCImplDecl *IMD =
1964 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001965 return IMD->getClassInterface();
1966
Craig Topper36250ad2014-05-12 05:36:57 +00001967 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001968}
1969
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001970/// \brief Get the copy initialization expression of VarDecl,or NULL if
1971/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001972Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001973 assert(VD && "Passed null params");
1974 assert(VD->hasAttr<BlocksAttr>() &&
1975 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001976 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001977 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001978 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001979}
1980
1981/// \brief Set the copy inialization expression of a block var decl.
1982void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1983 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001984 assert(VD->hasAttr<BlocksAttr>() &&
1985 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001986 BlockVarCopyInits[VD] = Init;
1987}
1988
John McCallbcd03502009-12-07 02:54:59 +00001989TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001990 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001991 if (!DataSize)
1992 DataSize = TypeLoc::getFullDataSizeForType(T);
1993 else
1994 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001995 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001996
John McCallbcd03502009-12-07 02:54:59 +00001997 TypeSourceInfo *TInfo =
1998 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1999 new (TInfo) TypeSourceInfo(T);
2000 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002001}
2002
John McCallbcd03502009-12-07 02:54:59 +00002003TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002004 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002005 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002006 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002007 return DI;
2008}
2009
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002010const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002011ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002012 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002013}
2014
2015const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002016ASTContext::getASTObjCImplementationLayout(
2017 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002018 return getObjCLayout(D->getClassInterface(), D);
2019}
2020
Chris Lattner983a8bb2007-07-13 22:13:22 +00002021//===----------------------------------------------------------------------===//
2022// Type creation/memoization methods
2023//===----------------------------------------------------------------------===//
2024
Jay Foad39c79802011-01-12 09:06:06 +00002025QualType
John McCall33ddac02011-01-19 10:06:00 +00002026ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2027 unsigned fastQuals = quals.getFastQualifiers();
2028 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002029
2030 // Check if we've already instantiated this type.
2031 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002032 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002033 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002034 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2035 assert(eq->getQualifiers() == quals);
2036 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002037 }
2038
John McCall33ddac02011-01-19 10:06:00 +00002039 // If the base type is not canonical, make the appropriate canonical type.
2040 QualType canon;
2041 if (!baseType->isCanonicalUnqualified()) {
2042 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002043 canonSplit.Quals.addConsistentQualifiers(quals);
2044 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002045
2046 // Re-find the insert position.
2047 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2048 }
2049
2050 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2051 ExtQualNodes.InsertNode(eq, insertPos);
2052 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002053}
2054
Jay Foad39c79802011-01-12 09:06:06 +00002055QualType
2056ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002057 QualType CanT = getCanonicalType(T);
2058 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002059 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002060
John McCall8ccfcb52009-09-24 19:53:00 +00002061 // If we are composing extended qualifiers together, merge together
2062 // into one ExtQuals node.
2063 QualifierCollector Quals;
2064 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002065
John McCall8ccfcb52009-09-24 19:53:00 +00002066 // If this type already has an address space specified, it cannot get
2067 // another one.
2068 assert(!Quals.hasAddressSpace() &&
2069 "Type cannot be in multiple addr spaces!");
2070 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002071
John McCall8ccfcb52009-09-24 19:53:00 +00002072 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002073}
2074
Chris Lattnerd60183d2009-02-18 22:53:11 +00002075QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002076 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002077 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002078 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002079 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002080
John McCall53fa7142010-12-24 02:08:15 +00002081 if (const PointerType *ptr = T->getAs<PointerType>()) {
2082 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002083 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002084 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2085 return getPointerType(ResultType);
2086 }
2087 }
Mike Stump11289f42009-09-09 15:08:12 +00002088
John McCall8ccfcb52009-09-24 19:53:00 +00002089 // If we are composing extended qualifiers together, merge together
2090 // into one ExtQuals node.
2091 QualifierCollector Quals;
2092 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002093
John McCall8ccfcb52009-09-24 19:53:00 +00002094 // If this type already has an ObjCGC specified, it cannot get
2095 // another one.
2096 assert(!Quals.hasObjCGCAttr() &&
2097 "Type cannot have multiple ObjCGCs!");
2098 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002099
John McCall8ccfcb52009-09-24 19:53:00 +00002100 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002101}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002102
John McCall4f5019e2010-12-19 02:44:49 +00002103const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2104 FunctionType::ExtInfo Info) {
2105 if (T->getExtInfo() == Info)
2106 return T;
2107
2108 QualType Result;
2109 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002110 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002111 } else {
2112 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2113 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2114 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002115 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002116 }
2117
2118 return cast<FunctionType>(Result.getTypePtr());
2119}
2120
Richard Smith2a7d4812013-05-04 07:00:32 +00002121void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2122 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002123 FD = FD->getMostRecentDecl();
2124 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002125 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2126 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002127 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002128 if (FunctionDecl *Next = FD->getPreviousDecl())
2129 FD = Next;
2130 else
2131 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002132 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002133 if (ASTMutationListener *L = getASTMutationListener())
2134 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002135}
2136
Richard Smith0b3a4622014-11-13 20:01:57 +00002137/// Get a function type and produce the equivalent function type with the
2138/// specified exception specification. Type sugar that can be present on a
2139/// declaration of a function with an exception specification is permitted
2140/// and preserved. Other type sugar (for instance, typedefs) is not.
2141static QualType getFunctionTypeWithExceptionSpec(
2142 ASTContext &Context, QualType Orig,
2143 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2144 // Might have some parens.
2145 if (auto *PT = dyn_cast<ParenType>(Orig))
2146 return Context.getParenType(
2147 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2148
2149 // Might have a calling-convention attribute.
2150 if (auto *AT = dyn_cast<AttributedType>(Orig))
2151 return Context.getAttributedType(
2152 AT->getAttrKind(),
2153 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2154 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2155 ESI));
2156
2157 // Anything else must be a function type. Rebuild it with the new exception
2158 // specification.
2159 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2160 return Context.getFunctionType(
2161 Proto->getReturnType(), Proto->getParamTypes(),
2162 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2163}
2164
2165void ASTContext::adjustExceptionSpec(
2166 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2167 bool AsWritten) {
2168 // Update the type.
2169 QualType Updated =
2170 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2171 FD->setType(Updated);
2172
2173 if (!AsWritten)
2174 return;
2175
2176 // Update the type in the type source information too.
2177 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2178 // If the type and the type-as-written differ, we may need to update
2179 // the type-as-written too.
2180 if (TSInfo->getType() != FD->getType())
2181 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2182
2183 // FIXME: When we get proper type location information for exceptions,
2184 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2185 // up the TypeSourceInfo;
2186 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2187 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2188 "TypeLoc size mismatch from updating exception specification");
2189 TSInfo->overrideType(Updated);
2190 }
2191}
2192
Chris Lattnerc6395932007-06-22 20:56:16 +00002193/// getComplexType - Return the uniqued reference to the type for a complex
2194/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002195QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002196 // Unique pointers, to guarantee there is only one pointer of a particular
2197 // structure.
2198 llvm::FoldingSetNodeID ID;
2199 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002200
Craig Topper36250ad2014-05-12 05:36:57 +00002201 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002202 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2203 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002204
Chris Lattnerc6395932007-06-22 20:56:16 +00002205 // If the pointee type isn't canonical, this won't be a canonical type either,
2206 // so fill in the canonical type field.
2207 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002208 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002209 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnerc6395932007-06-22 20:56:16 +00002211 // Get the new insert position for the node we care about.
2212 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002213 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002214 }
John McCall90d1c2d2009-09-24 23:30:46 +00002215 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002216 Types.push_back(New);
2217 ComplexTypes.InsertNode(New, InsertPos);
2218 return QualType(New, 0);
2219}
2220
Chris Lattner970e54e2006-11-12 00:37:36 +00002221/// getPointerType - Return the uniqued reference to the type for a pointer to
2222/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002223QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002224 // Unique pointers, to guarantee there is only one pointer of a particular
2225 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002226 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002227 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002228
Craig Topper36250ad2014-05-12 05:36:57 +00002229 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002230 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002231 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002232
Chris Lattner7ccecb92006-11-12 08:50:50 +00002233 // If the pointee type isn't canonical, this won't be a canonical type either,
2234 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002235 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002236 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002237 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002238
Bob Wilsonc8541f22013-03-15 17:12:43 +00002239 // Get the new insert position for the node we care about.
2240 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002241 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002242 }
John McCall90d1c2d2009-09-24 23:30:46 +00002243 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002244 Types.push_back(New);
2245 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002246 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002247}
2248
Reid Kleckner0503a872013-12-05 01:23:43 +00002249QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2250 llvm::FoldingSetNodeID ID;
2251 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002252 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002253 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2254 if (AT)
2255 return QualType(AT, 0);
2256
2257 QualType Canonical = getCanonicalType(New);
2258
2259 // Get the new insert position for the node we care about.
2260 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002261 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002262
2263 AT = new (*this, TypeAlignment)
2264 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2265 Types.push_back(AT);
2266 AdjustedTypes.InsertNode(AT, InsertPos);
2267 return QualType(AT, 0);
2268}
2269
Reid Kleckner8a365022013-06-24 17:51:48 +00002270QualType ASTContext::getDecayedType(QualType T) const {
2271 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2272
Reid Kleckner8a365022013-06-24 17:51:48 +00002273 QualType Decayed;
2274
2275 // C99 6.7.5.3p7:
2276 // A declaration of a parameter as "array of type" shall be
2277 // adjusted to "qualified pointer to type", where the type
2278 // qualifiers (if any) are those specified within the [ and ] of
2279 // the array type derivation.
2280 if (T->isArrayType())
2281 Decayed = getArrayDecayedType(T);
2282
2283 // C99 6.7.5.3p8:
2284 // A declaration of a parameter as "function returning type"
2285 // shall be adjusted to "pointer to function returning type", as
2286 // in 6.3.2.1.
2287 if (T->isFunctionType())
2288 Decayed = getPointerType(T);
2289
Reid Kleckner0503a872013-12-05 01:23:43 +00002290 llvm::FoldingSetNodeID ID;
2291 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002292 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002293 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2294 if (AT)
2295 return QualType(AT, 0);
2296
Reid Kleckner8a365022013-06-24 17:51:48 +00002297 QualType Canonical = getCanonicalType(Decayed);
2298
2299 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002300 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002301 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002302
Reid Kleckner0503a872013-12-05 01:23:43 +00002303 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2304 Types.push_back(AT);
2305 AdjustedTypes.InsertNode(AT, InsertPos);
2306 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002307}
2308
Mike Stump11289f42009-09-09 15:08:12 +00002309/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002310/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002311QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002312 assert(T->isFunctionType() && "block of function types only");
2313 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002314 // structure.
2315 llvm::FoldingSetNodeID ID;
2316 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002317
Craig Topper36250ad2014-05-12 05:36:57 +00002318 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002319 if (BlockPointerType *PT =
2320 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2321 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002322
2323 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002324 // type either so fill in the canonical type field.
2325 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002326 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002327 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002328
Steve Naroffec33ed92008-08-27 16:04:49 +00002329 // Get the new insert position for the node we care about.
2330 BlockPointerType *NewIP =
2331 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002332 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002333 }
John McCall90d1c2d2009-09-24 23:30:46 +00002334 BlockPointerType *New
2335 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002336 Types.push_back(New);
2337 BlockPointerTypes.InsertNode(New, InsertPos);
2338 return QualType(New, 0);
2339}
2340
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002341/// getLValueReferenceType - Return the uniqued reference to the type for an
2342/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002343QualType
2344ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002345 assert(getCanonicalType(T) != OverloadTy &&
2346 "Unresolved overloaded function type");
2347
Bill Wendling3708c182007-05-27 10:15:43 +00002348 // Unique pointers, to guarantee there is only one pointer of a particular
2349 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002350 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002351 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002352
Craig Topper36250ad2014-05-12 05:36:57 +00002353 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002354 if (LValueReferenceType *RT =
2355 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002356 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002357
John McCallfc93cf92009-10-22 22:37:11 +00002358 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2359
Bill Wendling3708c182007-05-27 10:15:43 +00002360 // If the referencee type isn't canonical, this won't be a canonical type
2361 // either, so fill in the canonical type field.
2362 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002363 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2364 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2365 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002366
Bill Wendling3708c182007-05-27 10:15:43 +00002367 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002368 LValueReferenceType *NewIP =
2369 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002370 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002371 }
2372
John McCall90d1c2d2009-09-24 23:30:46 +00002373 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002374 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2375 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002376 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002377 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002378
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002379 return QualType(New, 0);
2380}
2381
2382/// getRValueReferenceType - Return the uniqued reference to the type for an
2383/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002384QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002385 // Unique pointers, to guarantee there is only one pointer of a particular
2386 // structure.
2387 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002388 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002389
Craig Topper36250ad2014-05-12 05:36:57 +00002390 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002391 if (RValueReferenceType *RT =
2392 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2393 return QualType(RT, 0);
2394
John McCallfc93cf92009-10-22 22:37:11 +00002395 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2396
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002397 // If the referencee type isn't canonical, this won't be a canonical type
2398 // either, so fill in the canonical type field.
2399 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002400 if (InnerRef || !T.isCanonical()) {
2401 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2402 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002403
2404 // Get the new insert position for the node we care about.
2405 RValueReferenceType *NewIP =
2406 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002407 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002408 }
2409
John McCall90d1c2d2009-09-24 23:30:46 +00002410 RValueReferenceType *New
2411 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002412 Types.push_back(New);
2413 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002414 return QualType(New, 0);
2415}
2416
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002417/// getMemberPointerType - Return the uniqued reference to the type for a
2418/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002419QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002420 // Unique pointers, to guarantee there is only one pointer of a particular
2421 // structure.
2422 llvm::FoldingSetNodeID ID;
2423 MemberPointerType::Profile(ID, T, Cls);
2424
Craig Topper36250ad2014-05-12 05:36:57 +00002425 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002426 if (MemberPointerType *PT =
2427 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2428 return QualType(PT, 0);
2429
2430 // If the pointee or class type isn't canonical, this won't be a canonical
2431 // type either, so fill in the canonical type field.
2432 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002433 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002434 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2435
2436 // Get the new insert position for the node we care about.
2437 MemberPointerType *NewIP =
2438 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002439 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002440 }
John McCall90d1c2d2009-09-24 23:30:46 +00002441 MemberPointerType *New
2442 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002443 Types.push_back(New);
2444 MemberPointerTypes.InsertNode(New, InsertPos);
2445 return QualType(New, 0);
2446}
2447
Mike Stump11289f42009-09-09 15:08:12 +00002448/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002449/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002450QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002451 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002452 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002453 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002454 assert((EltTy->isDependentType() ||
2455 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002456 "Constant array of VLAs is illegal!");
2457
Chris Lattnere2df3f92009-05-13 04:12:56 +00002458 // Convert the array size into a canonical width matching the pointer size for
2459 // the target.
2460 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002461 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002462 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002463
Chris Lattner23b7eb62007-06-15 23:05:46 +00002464 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002465 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002466
Craig Topper36250ad2014-05-12 05:36:57 +00002467 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002468 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002469 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002470 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002471
John McCall33ddac02011-01-19 10:06:00 +00002472 // If the element type isn't canonical or has qualifiers, this won't
2473 // be a canonical type either, so fill in the canonical type field.
2474 QualType Canon;
2475 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2476 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002477 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002478 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002479 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002480
Chris Lattner36f8e652007-01-27 08:31:04 +00002481 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002482 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002483 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002484 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002485 }
Mike Stump11289f42009-09-09 15:08:12 +00002486
John McCall90d1c2d2009-09-24 23:30:46 +00002487 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002488 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002489 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002490 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002491 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002492}
2493
John McCall06549462011-01-18 08:40:38 +00002494/// getVariableArrayDecayedType - Turns the given type, which may be
2495/// variably-modified, into the corresponding type with all the known
2496/// sizes replaced with [*].
2497QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2498 // Vastly most common case.
2499 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002500
John McCall06549462011-01-18 08:40:38 +00002501 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002502
John McCall06549462011-01-18 08:40:38 +00002503 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002504 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002505 switch (ty->getTypeClass()) {
2506#define TYPE(Class, Base)
2507#define ABSTRACT_TYPE(Class, Base)
2508#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2509#include "clang/AST/TypeNodes.def"
2510 llvm_unreachable("didn't desugar past all non-canonical types?");
2511
2512 // These types should never be variably-modified.
2513 case Type::Builtin:
2514 case Type::Complex:
2515 case Type::Vector:
2516 case Type::ExtVector:
2517 case Type::DependentSizedExtVector:
2518 case Type::ObjCObject:
2519 case Type::ObjCInterface:
2520 case Type::ObjCObjectPointer:
2521 case Type::Record:
2522 case Type::Enum:
2523 case Type::UnresolvedUsing:
2524 case Type::TypeOfExpr:
2525 case Type::TypeOf:
2526 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002527 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002528 case Type::DependentName:
2529 case Type::InjectedClassName:
2530 case Type::TemplateSpecialization:
2531 case Type::DependentTemplateSpecialization:
2532 case Type::TemplateTypeParm:
2533 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002534 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002535 case Type::PackExpansion:
2536 llvm_unreachable("type should never be variably-modified");
2537
2538 // These types can be variably-modified but should never need to
2539 // further decay.
2540 case Type::FunctionNoProto:
2541 case Type::FunctionProto:
2542 case Type::BlockPointer:
2543 case Type::MemberPointer:
2544 return type;
2545
2546 // These types can be variably-modified. All these modifications
2547 // preserve structure except as noted by comments.
2548 // TODO: if we ever care about optimizing VLAs, there are no-op
2549 // optimizations available here.
2550 case Type::Pointer:
2551 result = getPointerType(getVariableArrayDecayedType(
2552 cast<PointerType>(ty)->getPointeeType()));
2553 break;
2554
2555 case Type::LValueReference: {
2556 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2557 result = getLValueReferenceType(
2558 getVariableArrayDecayedType(lv->getPointeeType()),
2559 lv->isSpelledAsLValue());
2560 break;
2561 }
2562
2563 case Type::RValueReference: {
2564 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2565 result = getRValueReferenceType(
2566 getVariableArrayDecayedType(lv->getPointeeType()));
2567 break;
2568 }
2569
Eli Friedman0dfb8892011-10-06 23:00:33 +00002570 case Type::Atomic: {
2571 const AtomicType *at = cast<AtomicType>(ty);
2572 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2573 break;
2574 }
2575
John McCall06549462011-01-18 08:40:38 +00002576 case Type::ConstantArray: {
2577 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2578 result = getConstantArrayType(
2579 getVariableArrayDecayedType(cat->getElementType()),
2580 cat->getSize(),
2581 cat->getSizeModifier(),
2582 cat->getIndexTypeCVRQualifiers());
2583 break;
2584 }
2585
2586 case Type::DependentSizedArray: {
2587 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2588 result = getDependentSizedArrayType(
2589 getVariableArrayDecayedType(dat->getElementType()),
2590 dat->getSizeExpr(),
2591 dat->getSizeModifier(),
2592 dat->getIndexTypeCVRQualifiers(),
2593 dat->getBracketsRange());
2594 break;
2595 }
2596
2597 // Turn incomplete types into [*] types.
2598 case Type::IncompleteArray: {
2599 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2600 result = getVariableArrayType(
2601 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002602 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002603 ArrayType::Normal,
2604 iat->getIndexTypeCVRQualifiers(),
2605 SourceRange());
2606 break;
2607 }
2608
2609 // Turn VLA types into [*] types.
2610 case Type::VariableArray: {
2611 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2612 result = getVariableArrayType(
2613 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002614 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002615 ArrayType::Star,
2616 vat->getIndexTypeCVRQualifiers(),
2617 vat->getBracketsRange());
2618 break;
2619 }
2620 }
2621
2622 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002623 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002624}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002625
Steve Naroffcadebd02007-08-30 18:14:25 +00002626/// getVariableArrayType - Returns a non-unique reference to the type for a
2627/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002628QualType ASTContext::getVariableArrayType(QualType EltTy,
2629 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002630 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002631 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002632 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002633 // Since we don't unique expressions, it isn't possible to unique VLA's
2634 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002635 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002636
John McCall33ddac02011-01-19 10:06:00 +00002637 // Be sure to pull qualifiers off the element type.
2638 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2639 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002640 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002641 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002642 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002643 }
2644
John McCall90d1c2d2009-09-24 23:30:46 +00002645 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002646 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002647
2648 VariableArrayTypes.push_back(New);
2649 Types.push_back(New);
2650 return QualType(New, 0);
2651}
2652
Douglas Gregor4619e432008-12-05 23:32:09 +00002653/// getDependentSizedArrayType - Returns a non-unique reference to
2654/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002655/// type.
John McCall33ddac02011-01-19 10:06:00 +00002656QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2657 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002658 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002659 unsigned elementTypeQuals,
2660 SourceRange brackets) const {
2661 assert((!numElements || numElements->isTypeDependent() ||
2662 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002663 "Size must be type- or value-dependent!");
2664
John McCall33ddac02011-01-19 10:06:00 +00002665 // Dependently-sized array types that do not have a specified number
2666 // of elements will have their sizes deduced from a dependent
2667 // initializer. We do no canonicalization here at all, which is okay
2668 // because they can't be used in most locations.
2669 if (!numElements) {
2670 DependentSizedArrayType *newType
2671 = new (*this, TypeAlignment)
2672 DependentSizedArrayType(*this, elementType, QualType(),
2673 numElements, ASM, elementTypeQuals,
2674 brackets);
2675 Types.push_back(newType);
2676 return QualType(newType, 0);
2677 }
2678
2679 // Otherwise, we actually build a new type every time, but we
2680 // also build a canonical type.
2681
2682 SplitQualType canonElementType = getCanonicalType(elementType).split();
2683
Craig Topper36250ad2014-05-12 05:36:57 +00002684 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002685 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002686 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002687 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002688 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002689
John McCall33ddac02011-01-19 10:06:00 +00002690 // Look for an existing type with these properties.
2691 DependentSizedArrayType *canonTy =
2692 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002693
John McCall33ddac02011-01-19 10:06:00 +00002694 // If we don't have one, build one.
2695 if (!canonTy) {
2696 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002697 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002698 QualType(), numElements, ASM, elementTypeQuals,
2699 brackets);
2700 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2701 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002702 }
2703
John McCall33ddac02011-01-19 10:06:00 +00002704 // Apply qualifiers from the element type to the array.
2705 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002706 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002707
John McCall33ddac02011-01-19 10:06:00 +00002708 // If we didn't need extra canonicalization for the element type,
2709 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002710 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002711 return canon;
2712
2713 // Otherwise, we need to build a type which follows the spelling
2714 // of the element type.
2715 DependentSizedArrayType *sugaredType
2716 = new (*this, TypeAlignment)
2717 DependentSizedArrayType(*this, elementType, canon, numElements,
2718 ASM, elementTypeQuals, brackets);
2719 Types.push_back(sugaredType);
2720 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002721}
2722
John McCall33ddac02011-01-19 10:06:00 +00002723QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002724 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002725 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002726 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002727 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002728
Craig Topper36250ad2014-05-12 05:36:57 +00002729 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002730 if (IncompleteArrayType *iat =
2731 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2732 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002733
2734 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002735 // either, so fill in the canonical type field. We also have to pull
2736 // qualifiers off the element type.
2737 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002738
John McCall33ddac02011-01-19 10:06:00 +00002739 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2740 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002741 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002742 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002743 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002744
2745 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002746 IncompleteArrayType *existing =
2747 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2748 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002749 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002750
John McCall33ddac02011-01-19 10:06:00 +00002751 IncompleteArrayType *newType = new (*this, TypeAlignment)
2752 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002753
John McCall33ddac02011-01-19 10:06:00 +00002754 IncompleteArrayTypes.InsertNode(newType, insertPos);
2755 Types.push_back(newType);
2756 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002757}
2758
Steve Naroff91fcddb2007-07-18 18:00:27 +00002759/// getVectorType - Return the unique reference to a vector type of
2760/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002761QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002762 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002763 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002764
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002765 // Check if we've already instantiated a vector of this type.
2766 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002767 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002768
Craig Topper36250ad2014-05-12 05:36:57 +00002769 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002770 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2771 return QualType(VTP, 0);
2772
2773 // If the element type isn't canonical, this won't be a canonical type either,
2774 // so fill in the canonical type field.
2775 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002776 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002777 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002778
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002779 // Get the new insert position for the node we care about.
2780 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002781 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002782 }
John McCall90d1c2d2009-09-24 23:30:46 +00002783 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002784 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002785 VectorTypes.InsertNode(New, InsertPos);
2786 Types.push_back(New);
2787 return QualType(New, 0);
2788}
2789
Nate Begemance4d7fc2008-04-18 23:10:10 +00002790/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002791/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002792QualType
2793ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002794 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002795
Steve Naroff91fcddb2007-07-18 18:00:27 +00002796 // Check if we've already instantiated a vector of this type.
2797 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002798 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002799 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002800 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002801 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2802 return QualType(VTP, 0);
2803
2804 // If the element type isn't canonical, this won't be a canonical type either,
2805 // so fill in the canonical type field.
2806 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002807 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002808 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002809
Steve Naroff91fcddb2007-07-18 18:00:27 +00002810 // Get the new insert position for the node we care about.
2811 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002812 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002813 }
John McCall90d1c2d2009-09-24 23:30:46 +00002814 ExtVectorType *New = new (*this, TypeAlignment)
2815 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002816 VectorTypes.InsertNode(New, InsertPos);
2817 Types.push_back(New);
2818 return QualType(New, 0);
2819}
2820
Jay Foad39c79802011-01-12 09:06:06 +00002821QualType
2822ASTContext::getDependentSizedExtVectorType(QualType vecType,
2823 Expr *SizeExpr,
2824 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002825 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002826 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002827 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002828
Craig Topper36250ad2014-05-12 05:36:57 +00002829 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002830 DependentSizedExtVectorType *Canon
2831 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2832 DependentSizedExtVectorType *New;
2833 if (Canon) {
2834 // We already have a canonical version of this array type; use it as
2835 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002836 New = new (*this, TypeAlignment)
2837 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2838 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002839 } else {
2840 QualType CanonVecTy = getCanonicalType(vecType);
2841 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002842 New = new (*this, TypeAlignment)
2843 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2844 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002845
2846 DependentSizedExtVectorType *CanonCheck
2847 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2848 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2849 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002850 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2851 } else {
2852 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2853 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002854 New = new (*this, TypeAlignment)
2855 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002856 }
2857 }
Mike Stump11289f42009-09-09 15:08:12 +00002858
Douglas Gregor758a8692009-06-17 21:51:59 +00002859 Types.push_back(New);
2860 return QualType(New, 0);
2861}
2862
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002863/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002864///
Jay Foad39c79802011-01-12 09:06:06 +00002865QualType
2866ASTContext::getFunctionNoProtoType(QualType ResultTy,
2867 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002868 const CallingConv CallConv = Info.getCC();
2869
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002870 // Unique functions, to guarantee there is only one function of a particular
2871 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002872 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002873 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002874
Craig Topper36250ad2014-05-12 05:36:57 +00002875 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002876 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002877 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002878 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002879
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002880 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002881 if (!ResultTy.isCanonical()) {
2882 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002883
Chris Lattner47955de2007-01-27 08:37:20 +00002884 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002885 FunctionNoProtoType *NewIP =
2886 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002887 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002888 }
Mike Stump11289f42009-09-09 15:08:12 +00002889
Roman Divacky65b88cd2011-03-01 17:40:53 +00002890 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002891 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002892 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002893 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002894 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002895 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002896}
2897
Douglas Gregorcd780372013-01-17 23:36:45 +00002898/// \brief Determine whether \p T is canonical as the result type of a function.
2899static bool isCanonicalResultType(QualType T) {
2900 return T.isCanonical() &&
2901 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2902 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2903}
2904
Jay Foad39c79802011-01-12 09:06:06 +00002905QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002906ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002907 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002908 size_t NumArgs = ArgArray.size();
2909
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002910 // Unique functions, to guarantee there is only one function of a particular
2911 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002912 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002913 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2914 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002915
Craig Topper36250ad2014-05-12 05:36:57 +00002916 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002917 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002918 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002919 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002920
2921 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002922 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002923 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002924 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002925 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002926 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002927 isCanonical = false;
2928
2929 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002930 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002931 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002932 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002933 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002934 CanonicalArgs.reserve(NumArgs);
2935 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002936 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002937
John McCalldb40c7f2010-12-14 08:05:40 +00002938 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002939 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002940 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002941
Douglas Gregorcd780372013-01-17 23:36:45 +00002942 // Result types do not have ARC lifetime qualifiers.
2943 QualType CanResultTy = getCanonicalType(ResultTy);
2944 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2945 Qualifiers Qs = CanResultTy.getQualifiers();
2946 Qs.removeObjCLifetime();
2947 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2948 }
2949
Jordan Rose5c382722013-03-08 21:51:21 +00002950 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002951
Chris Lattnerfd4de792007-01-27 01:15:32 +00002952 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002953 FunctionProtoType *NewIP =
2954 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002955 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002956 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002957
John McCall31168b02011-06-15 23:02:42 +00002958 // FunctionProtoType objects are allocated with extra bytes after
2959 // them for three variable size arrays at the end:
2960 // - parameter types
2961 // - exception types
2962 // - consumed-arguments flags
2963 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002964 // expression, or information used to resolve the exception
2965 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002966 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002967 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00002968 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2969 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2970 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002971 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00002972 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002973 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00002974 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002975 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002976 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002977 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002978 Size += NumArgs * sizeof(bool);
2979
John McCalldb40c7f2010-12-14 08:05:40 +00002980 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002981 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002982 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002983 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002984 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002985 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002986}
Chris Lattneref51c202006-11-10 07:17:23 +00002987
John McCalle78aac42010-03-10 03:28:59 +00002988#ifndef NDEBUG
2989static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2990 if (!isa<CXXRecordDecl>(D)) return false;
2991 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2992 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2993 return true;
2994 if (RD->getDescribedClassTemplate() &&
2995 !isa<ClassTemplateSpecializationDecl>(RD))
2996 return true;
2997 return false;
2998}
2999#endif
3000
3001/// getInjectedClassNameType - Return the unique reference to the
3002/// injected class name type for the specified templated declaration.
3003QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003004 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003005 assert(NeedsInjectedClassNameType(Decl));
3006 if (Decl->TypeForDecl) {
3007 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003008 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003009 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3010 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3011 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3012 } else {
John McCall424cec92011-01-19 06:33:43 +00003013 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003014 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003015 Decl->TypeForDecl = newType;
3016 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003017 }
3018 return QualType(Decl->TypeForDecl, 0);
3019}
3020
Douglas Gregor83a586e2008-04-13 21:07:44 +00003021/// getTypeDeclType - Return the unique reference to the type for the
3022/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003023QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003024 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003025 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003026
Richard Smithdda56e42011-04-15 14:24:37 +00003027 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003028 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003029
John McCall96f0b5f2010-03-10 06:48:02 +00003030 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3031 "Template type parameter types are always available.");
3032
John McCall81e38502010-02-16 03:57:14 +00003033 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003034 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003035 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003036 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003037 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003038 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003039 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003040 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003041 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003042 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3043 Decl->TypeForDecl = newType;
3044 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003045 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003046 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003047
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003048 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003049}
3050
Chris Lattner32d920b2007-01-26 02:01:53 +00003051/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003052/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003053QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003054ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3055 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003056 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003057
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003058 if (Canonical.isNull())
3059 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003060 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003061 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003062 Decl->TypeForDecl = newType;
3063 Types.push_back(newType);
3064 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003065}
3066
Jay Foad39c79802011-01-12 09:06:06 +00003067QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003068 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3069
Douglas Gregorec9fd132012-01-14 16:38:05 +00003070 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003071 if (PrevDecl->TypeForDecl)
3072 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3073
John McCall424cec92011-01-19 06:33:43 +00003074 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3075 Decl->TypeForDecl = newType;
3076 Types.push_back(newType);
3077 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003078}
3079
Jay Foad39c79802011-01-12 09:06:06 +00003080QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003081 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3082
Douglas Gregorec9fd132012-01-14 16:38:05 +00003083 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003084 if (PrevDecl->TypeForDecl)
3085 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3086
John McCall424cec92011-01-19 06:33:43 +00003087 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3088 Decl->TypeForDecl = newType;
3089 Types.push_back(newType);
3090 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003091}
3092
John McCall81904512011-01-06 01:58:22 +00003093QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3094 QualType modifiedType,
3095 QualType equivalentType) {
3096 llvm::FoldingSetNodeID id;
3097 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3098
Craig Topper36250ad2014-05-12 05:36:57 +00003099 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003100 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3101 if (type) return QualType(type, 0);
3102
3103 QualType canon = getCanonicalType(equivalentType);
3104 type = new (*this, TypeAlignment)
3105 AttributedType(canon, attrKind, modifiedType, equivalentType);
3106
3107 Types.push_back(type);
3108 AttributedTypes.InsertNode(type, insertPos);
3109
3110 return QualType(type, 0);
3111}
3112
3113
John McCallcebee162009-10-18 09:09:24 +00003114/// \brief Retrieve a substitution-result type.
3115QualType
3116ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003117 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003118 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003119 && "replacement types must always be canonical");
3120
3121 llvm::FoldingSetNodeID ID;
3122 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003123 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003124 SubstTemplateTypeParmType *SubstParm
3125 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3126
3127 if (!SubstParm) {
3128 SubstParm = new (*this, TypeAlignment)
3129 SubstTemplateTypeParmType(Parm, Replacement);
3130 Types.push_back(SubstParm);
3131 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3132 }
3133
3134 return QualType(SubstParm, 0);
3135}
3136
Douglas Gregorada4b792011-01-14 02:55:32 +00003137/// \brief Retrieve a
3138QualType ASTContext::getSubstTemplateTypeParmPackType(
3139 const TemplateTypeParmType *Parm,
3140 const TemplateArgument &ArgPack) {
3141#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003142 for (const auto &P : ArgPack.pack_elements()) {
3143 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3144 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003145 }
3146#endif
3147
3148 llvm::FoldingSetNodeID ID;
3149 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003150 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003151 if (SubstTemplateTypeParmPackType *SubstParm
3152 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3153 return QualType(SubstParm, 0);
3154
3155 QualType Canon;
3156 if (!Parm->isCanonicalUnqualified()) {
3157 Canon = getCanonicalType(QualType(Parm, 0));
3158 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3159 ArgPack);
3160 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3161 }
3162
3163 SubstTemplateTypeParmPackType *SubstParm
3164 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3165 ArgPack);
3166 Types.push_back(SubstParm);
3167 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3168 return QualType(SubstParm, 0);
3169}
3170
Douglas Gregoreff93e02009-02-05 23:33:38 +00003171/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003172/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003173/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003174QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003175 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003176 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003177 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003178 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003179 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003180 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003181 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3182
3183 if (TypeParm)
3184 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003185
Chandler Carruth08836322011-05-01 00:51:33 +00003186 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003187 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003188 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003189
3190 TemplateTypeParmType *TypeCheck
3191 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3192 assert(!TypeCheck && "Template type parameter canonical type broken");
3193 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003194 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003195 TypeParm = new (*this, TypeAlignment)
3196 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003197
3198 Types.push_back(TypeParm);
3199 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3200
3201 return QualType(TypeParm, 0);
3202}
3203
John McCalle78aac42010-03-10 03:28:59 +00003204TypeSourceInfo *
3205ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3206 SourceLocation NameLoc,
3207 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003208 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003209 assert(!Name.getAsDependentTemplateName() &&
3210 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003211 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003212
3213 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003214 TemplateSpecializationTypeLoc TL =
3215 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003216 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003217 TL.setTemplateNameLoc(NameLoc);
3218 TL.setLAngleLoc(Args.getLAngleLoc());
3219 TL.setRAngleLoc(Args.getRAngleLoc());
3220 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3221 TL.setArgLocInfo(i, Args[i].getLocInfo());
3222 return DI;
3223}
3224
Mike Stump11289f42009-09-09 15:08:12 +00003225QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003226ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003227 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003228 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003229 assert(!Template.getAsDependentTemplateName() &&
3230 "No dependent template names here!");
3231
John McCall6b51f282009-11-23 01:53:49 +00003232 unsigned NumArgs = Args.size();
3233
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003234 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003235 ArgVec.reserve(NumArgs);
3236 for (unsigned i = 0; i != NumArgs; ++i)
3237 ArgVec.push_back(Args[i].getArgument());
3238
John McCall2408e322010-04-27 00:57:59 +00003239 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003240 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003241}
3242
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003243#ifndef NDEBUG
3244static bool hasAnyPackExpansions(const TemplateArgument *Args,
3245 unsigned NumArgs) {
3246 for (unsigned I = 0; I != NumArgs; ++I)
3247 if (Args[I].isPackExpansion())
3248 return true;
3249
3250 return true;
3251}
3252#endif
3253
John McCall0ad16662009-10-29 08:12:44 +00003254QualType
3255ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003256 const TemplateArgument *Args,
3257 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003258 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003259 assert(!Template.getAsDependentTemplateName() &&
3260 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003261 // Look through qualified template names.
3262 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3263 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003264
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003265 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003266 Template.getAsTemplateDecl() &&
3267 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003268 QualType CanonType;
3269 if (!Underlying.isNull())
3270 CanonType = getCanonicalType(Underlying);
3271 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003272 // We can get here with an alias template when the specialization contains
3273 // a pack expansion that does not match up with a parameter pack.
3274 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3275 "Caller must compute aliased type");
3276 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003277 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3278 NumArgs);
3279 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003280
Douglas Gregora8e02e72009-07-28 23:00:59 +00003281 // Allocate the (non-canonical) template specialization type, but don't
3282 // try to unique it: these types typically have location information that
3283 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003284 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3285 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003286 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003287 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003288 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003289 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3290 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003291
Douglas Gregor8bf42052009-02-09 18:46:07 +00003292 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003293 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003294}
3295
Mike Stump11289f42009-09-09 15:08:12 +00003296QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003297ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3298 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003299 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003300 assert(!Template.getAsDependentTemplateName() &&
3301 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003302
Douglas Gregore29139c2011-03-03 17:04:51 +00003303 // Look through qualified template names.
3304 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3305 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003306
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003307 // Build the canonical template specialization type.
3308 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003309 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003310 CanonArgs.reserve(NumArgs);
3311 for (unsigned I = 0; I != NumArgs; ++I)
3312 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3313
3314 // Determine whether this canonical template specialization type already
3315 // exists.
3316 llvm::FoldingSetNodeID ID;
3317 TemplateSpecializationType::Profile(ID, CanonTemplate,
3318 CanonArgs.data(), NumArgs, *this);
3319
Craig Topper36250ad2014-05-12 05:36:57 +00003320 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003321 TemplateSpecializationType *Spec
3322 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3323
3324 if (!Spec) {
3325 // Allocate a new canonical template specialization type.
3326 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3327 sizeof(TemplateArgument) * NumArgs),
3328 TypeAlignment);
3329 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3330 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003331 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003332 Types.push_back(Spec);
3333 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3334 }
3335
3336 assert(Spec->isDependentType() &&
3337 "Non-dependent template-id type must have a canonical type");
3338 return QualType(Spec, 0);
3339}
3340
3341QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003342ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3343 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003344 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003345 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003346 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003347
Craig Topper36250ad2014-05-12 05:36:57 +00003348 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003349 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003350 if (T)
3351 return QualType(T, 0);
3352
Douglas Gregorc42075a2010-02-04 18:10:26 +00003353 QualType Canon = NamedType;
3354 if (!Canon.isCanonical()) {
3355 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003356 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3357 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003358 (void)CheckT;
3359 }
3360
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003361 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003362 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003363 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003364 return QualType(T, 0);
3365}
3366
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003367QualType
Jay Foad39c79802011-01-12 09:06:06 +00003368ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003369 llvm::FoldingSetNodeID ID;
3370 ParenType::Profile(ID, InnerType);
3371
Craig Topper36250ad2014-05-12 05:36:57 +00003372 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003373 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3374 if (T)
3375 return QualType(T, 0);
3376
3377 QualType Canon = InnerType;
3378 if (!Canon.isCanonical()) {
3379 Canon = getCanonicalType(InnerType);
3380 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3381 assert(!CheckT && "Paren canonical type broken");
3382 (void)CheckT;
3383 }
3384
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003385 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003386 Types.push_back(T);
3387 ParenTypes.InsertNode(T, InsertPos);
3388 return QualType(T, 0);
3389}
3390
Douglas Gregor02085352010-03-31 20:19:30 +00003391QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3392 NestedNameSpecifier *NNS,
3393 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003394 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003395 if (Canon.isNull()) {
3396 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003397 ElaboratedTypeKeyword CanonKeyword = Keyword;
3398 if (Keyword == ETK_None)
3399 CanonKeyword = ETK_Typename;
3400
3401 if (CanonNNS != NNS || CanonKeyword != Keyword)
3402 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003403 }
3404
3405 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003406 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003407
Craig Topper36250ad2014-05-12 05:36:57 +00003408 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003409 DependentNameType *T
3410 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003411 if (T)
3412 return QualType(T, 0);
3413
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003414 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003415 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003416 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003417 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003418}
3419
Mike Stump11289f42009-09-09 15:08:12 +00003420QualType
John McCallc392f372010-06-11 00:33:02 +00003421ASTContext::getDependentTemplateSpecializationType(
3422 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003423 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003424 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003425 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003426 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003427 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003428 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3429 ArgCopy.push_back(Args[I].getArgument());
3430 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3431 ArgCopy.size(),
3432 ArgCopy.data());
3433}
3434
3435QualType
3436ASTContext::getDependentTemplateSpecializationType(
3437 ElaboratedTypeKeyword Keyword,
3438 NestedNameSpecifier *NNS,
3439 const IdentifierInfo *Name,
3440 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003441 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003442 assert((!NNS || NNS->isDependent()) &&
3443 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003444
Douglas Gregorc42075a2010-02-04 18:10:26 +00003445 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003446 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3447 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003448
Craig Topper36250ad2014-05-12 05:36:57 +00003449 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003450 DependentTemplateSpecializationType *T
3451 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003452 if (T)
3453 return QualType(T, 0);
3454
John McCallc392f372010-06-11 00:33:02 +00003455 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003456
John McCallc392f372010-06-11 00:33:02 +00003457 ElaboratedTypeKeyword CanonKeyword = Keyword;
3458 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3459
3460 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003461 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003462 for (unsigned I = 0; I != NumArgs; ++I) {
3463 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3464 if (!CanonArgs[I].structurallyEquals(Args[I]))
3465 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003466 }
3467
John McCallc392f372010-06-11 00:33:02 +00003468 QualType Canon;
3469 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3470 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3471 Name, NumArgs,
3472 CanonArgs.data());
3473
3474 // Find the insert position again.
3475 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3476 }
3477
3478 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3479 sizeof(TemplateArgument) * NumArgs),
3480 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003481 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003482 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003483 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003484 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003485 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003486}
3487
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003488QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003489 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003490 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003491 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003492
3493 assert(Pattern->containsUnexpandedParameterPack() &&
3494 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003495 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003496 PackExpansionType *T
3497 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3498 if (T)
3499 return QualType(T, 0);
3500
3501 QualType Canon;
3502 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003503 Canon = getCanonicalType(Pattern);
3504 // The canonical type might not contain an unexpanded parameter pack, if it
3505 // contains an alias template specialization which ignores one of its
3506 // parameters.
3507 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003508 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003509
Richard Smith68eea502012-07-16 00:20:35 +00003510 // Find the insert position again, in case we inserted an element into
3511 // PackExpansionTypes and invalidated our insert position.
3512 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3513 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003514 }
3515
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003516 T = new (*this, TypeAlignment)
3517 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003518 Types.push_back(T);
3519 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003520 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003521}
3522
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003523/// CmpProtocolNames - Comparison predicate for sorting protocols
3524/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003525static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3526 ObjCProtocolDecl *const *RHS) {
3527 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003528}
3529
John McCall8b07ec22010-05-15 11:32:37 +00003530static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003531 unsigned NumProtocols) {
3532 if (NumProtocols == 0) return true;
3533
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003534 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3535 return false;
3536
John McCallfc93cf92009-10-22 22:37:11 +00003537 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003538 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003539 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003540 return false;
3541 return true;
3542}
3543
3544static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003545 unsigned &NumProtocols) {
3546 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003547
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003548 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003549 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003550
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003551 // Canonicalize.
3552 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3553 Protocols[I] = Protocols[I]->getCanonicalDecl();
3554
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003555 // Remove duplicates.
3556 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3557 NumProtocols = ProtocolsEnd-Protocols;
3558}
3559
John McCall8b07ec22010-05-15 11:32:37 +00003560QualType ASTContext::getObjCObjectType(QualType BaseType,
3561 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003562 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003563 // If the base type is an interface and there aren't any protocols
3564 // to add, then the interface type will do just fine.
3565 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3566 return BaseType;
3567
3568 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003569 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003570 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003571 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003572 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3573 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003574
John McCall8b07ec22010-05-15 11:32:37 +00003575 // Build the canonical type, which has the canonical base type and
3576 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003577 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003578 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3579 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3580 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003581 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003582 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003583 unsigned UniqueCount = NumProtocols;
3584
John McCallfc93cf92009-10-22 22:37:11 +00003585 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003586 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3587 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003588 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003589 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3590 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003591 }
3592
3593 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003594 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3595 }
3596
3597 unsigned Size = sizeof(ObjCObjectTypeImpl);
3598 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3599 void *Mem = Allocate(Size, TypeAlignment);
3600 ObjCObjectTypeImpl *T =
3601 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3602
3603 Types.push_back(T);
3604 ObjCObjectTypes.InsertNode(T, InsertPos);
3605 return QualType(T, 0);
3606}
3607
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003608/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3609/// protocol list adopt all protocols in QT's qualified-id protocol
3610/// list.
3611bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3612 ObjCInterfaceDecl *IC) {
3613 if (!QT->isObjCQualifiedIdType())
3614 return false;
3615
3616 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3617 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003618 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003619 if (!IC->ClassImplementsProtocol(Proto, false))
3620 return false;
3621 }
3622 return true;
3623 }
3624 return false;
3625}
3626
3627/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3628/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3629/// of protocols.
3630bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3631 ObjCInterfaceDecl *IDecl) {
3632 if (!QT->isObjCQualifiedIdType())
3633 return false;
3634 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3635 if (!OPT)
3636 return false;
3637 if (!IDecl->hasDefinition())
3638 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003639 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3640 CollectInheritedProtocols(IDecl, InheritedProtocols);
3641 if (InheritedProtocols.empty())
3642 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003643 // Check that if every protocol in list of id<plist> conforms to a protcol
3644 // of IDecl's, then bridge casting is ok.
3645 bool Conforms = false;
3646 for (auto *Proto : OPT->quals()) {
3647 Conforms = false;
3648 for (auto *PI : InheritedProtocols) {
3649 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3650 Conforms = true;
3651 break;
3652 }
3653 }
3654 if (!Conforms)
3655 break;
3656 }
3657 if (Conforms)
3658 return true;
3659
Aaron Ballman83731462014-03-17 16:14:00 +00003660 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003661 // If both the right and left sides have qualifiers.
3662 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003663 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003664 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003665 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003666 break;
3667 }
3668 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003669 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003670 }
3671 return true;
3672}
3673
John McCall8b07ec22010-05-15 11:32:37 +00003674/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3675/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003676QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003677 llvm::FoldingSetNodeID ID;
3678 ObjCObjectPointerType::Profile(ID, ObjectT);
3679
Craig Topper36250ad2014-05-12 05:36:57 +00003680 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003681 if (ObjCObjectPointerType *QT =
3682 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3683 return QualType(QT, 0);
3684
3685 // Find the canonical object type.
3686 QualType Canonical;
3687 if (!ObjectT.isCanonical()) {
3688 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3689
3690 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003691 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3692 }
3693
Douglas Gregorf85bee62010-02-08 22:59:26 +00003694 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003695 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3696 ObjCObjectPointerType *QType =
3697 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003698
Steve Narofffb4330f2009-06-17 22:40:22 +00003699 Types.push_back(QType);
3700 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003701 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003702}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003703
Douglas Gregor1c283312010-08-11 12:19:30 +00003704/// getObjCInterfaceType - Return the unique reference to the type for the
3705/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003706QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3707 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003708 if (Decl->TypeForDecl)
3709 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003710
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003711 if (PrevDecl) {
3712 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3713 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3714 return QualType(PrevDecl->TypeForDecl, 0);
3715 }
3716
Douglas Gregor7671e532011-12-16 16:34:57 +00003717 // Prefer the definition, if there is one.
3718 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3719 Decl = Def;
3720
Douglas Gregor1c283312010-08-11 12:19:30 +00003721 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3722 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3723 Decl->TypeForDecl = T;
3724 Types.push_back(T);
3725 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003726}
3727
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003728/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3729/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003730/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003731/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003732/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003733QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003734 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003735 if (tofExpr->isTypeDependent()) {
3736 llvm::FoldingSetNodeID ID;
3737 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003738
Craig Topper36250ad2014-05-12 05:36:57 +00003739 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003740 DependentTypeOfExprType *Canon
3741 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3742 if (Canon) {
3743 // We already have a "canonical" version of an identical, dependent
3744 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003745 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003746 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003747 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003748 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003749 Canon
3750 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003751 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3752 toe = Canon;
3753 }
3754 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003755 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003756 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003757 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003758 Types.push_back(toe);
3759 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003760}
3761
Steve Naroffa773cd52007-08-01 18:02:17 +00003762/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003763/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003764/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003765/// an issue. This doesn't affect the type checker, since it operates
3766/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003767QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003768 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003769 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003770 Types.push_back(tot);
3771 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003772}
3773
Anders Carlssonad6bd352009-06-24 21:24:56 +00003774
Richard Smith8eb1d322014-06-05 20:13:13 +00003775/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3776/// nodes. This would never be helpful, since each such type has its own
3777/// expression, and would not give a significant memory saving, since there
3778/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003779QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003780 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003781
3782 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003783 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003784 // unique dependent type. Two such decltype-specifiers refer to the same
3785 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003786 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003787 llvm::FoldingSetNodeID ID;
3788 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003789
Craig Topper36250ad2014-05-12 05:36:57 +00003790 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003791 DependentDecltypeType *Canon
3792 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003793 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003794 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003795 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003796 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003797 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003798 dt = new (*this, TypeAlignment)
3799 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003800 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003801 dt = new (*this, TypeAlignment)
3802 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003803 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003804 Types.push_back(dt);
3805 return QualType(dt, 0);
3806}
3807
Alexis Hunte852b102011-05-24 22:41:36 +00003808/// getUnaryTransformationType - We don't unique these, since the memory
3809/// savings are minimal and these are rare.
3810QualType ASTContext::getUnaryTransformType(QualType BaseType,
3811 QualType UnderlyingType,
3812 UnaryTransformType::UTTKind Kind)
3813 const {
3814 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003815 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3816 Kind,
3817 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003818 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003819 Types.push_back(Ty);
3820 return QualType(Ty, 0);
3821}
3822
Richard Smith2a7d4812013-05-04 07:00:32 +00003823/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3824/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3825/// canonical deduced-but-dependent 'auto' type.
3826QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003827 bool IsDependent) const {
3828 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003829 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003830
Richard Smith2a7d4812013-05-04 07:00:32 +00003831 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003832 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003833 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003834 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003835 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3836 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003837
Richard Smith74aeef52013-04-26 16:15:35 +00003838 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003839 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003840 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003841 Types.push_back(AT);
3842 if (InsertPos)
3843 AutoTypes.InsertNode(AT, InsertPos);
3844 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003845}
3846
Eli Friedman0dfb8892011-10-06 23:00:33 +00003847/// getAtomicType - Return the uniqued reference to the atomic type for
3848/// the given value type.
3849QualType ASTContext::getAtomicType(QualType T) const {
3850 // Unique pointers, to guarantee there is only one pointer of a particular
3851 // structure.
3852 llvm::FoldingSetNodeID ID;
3853 AtomicType::Profile(ID, T);
3854
Craig Topper36250ad2014-05-12 05:36:57 +00003855 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003856 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3857 return QualType(AT, 0);
3858
3859 // If the atomic value type isn't canonical, this won't be a canonical type
3860 // either, so fill in the canonical type field.
3861 QualType Canonical;
3862 if (!T.isCanonical()) {
3863 Canonical = getAtomicType(getCanonicalType(T));
3864
3865 // Get the new insert position for the node we care about.
3866 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003867 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003868 }
3869 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3870 Types.push_back(New);
3871 AtomicTypes.InsertNode(New, InsertPos);
3872 return QualType(New, 0);
3873}
3874
Richard Smith02e85f32011-04-14 22:09:26 +00003875/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3876QualType ASTContext::getAutoDeductType() const {
3877 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003878 AutoDeductTy = QualType(
3879 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003880 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003881 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003882 return AutoDeductTy;
3883}
3884
3885/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3886QualType ASTContext::getAutoRRefDeductType() const {
3887 if (AutoRRefDeductTy.isNull())
3888 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3889 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3890 return AutoRRefDeductTy;
3891}
3892
Chris Lattnerfb072462007-01-23 05:45:31 +00003893/// getTagDeclType - Return the unique reference to the type for the
3894/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003895QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003896 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003897 // FIXME: What is the design on getTagDeclType when it requires casting
3898 // away const? mutable?
3899 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003900}
3901
Mike Stump11289f42009-09-09 15:08:12 +00003902/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3903/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3904/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003905CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003906 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003907}
Chris Lattnerfb072462007-01-23 05:45:31 +00003908
Hans Wennborg27541db2011-10-27 08:29:09 +00003909/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3910CanQualType ASTContext::getIntMaxType() const {
3911 return getFromTargetType(Target->getIntMaxType());
3912}
3913
3914/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3915CanQualType ASTContext::getUIntMaxType() const {
3916 return getFromTargetType(Target->getUIntMaxType());
3917}
3918
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003919/// getSignedWCharType - Return the type of "signed wchar_t".
3920/// Used when in C++, as a GCC extension.
3921QualType ASTContext::getSignedWCharType() const {
3922 // FIXME: derive from "Target" ?
3923 return WCharTy;
3924}
3925
3926/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3927/// Used when in C++, as a GCC extension.
3928QualType ASTContext::getUnsignedWCharType() const {
3929 // FIXME: derive from "Target" ?
3930 return UnsignedIntTy;
3931}
3932
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003933QualType ASTContext::getIntPtrType() const {
3934 return getFromTargetType(Target->getIntPtrType());
3935}
3936
3937QualType ASTContext::getUIntPtrType() const {
3938 return getCorrespondingUnsignedType(getIntPtrType());
3939}
3940
Hans Wennborg27541db2011-10-27 08:29:09 +00003941/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003942/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3943QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003944 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003945}
3946
Eli Friedman4e91899e2012-11-27 02:58:24 +00003947/// \brief Return the unique type for "pid_t" defined in
3948/// <sys/types.h>. We need this to compute the correct type for vfork().
3949QualType ASTContext::getProcessIDType() const {
3950 return getFromTargetType(Target->getProcessIDType());
3951}
3952
Chris Lattnera21ad802008-04-02 05:18:44 +00003953//===----------------------------------------------------------------------===//
3954// Type Operators
3955//===----------------------------------------------------------------------===//
3956
Jay Foad39c79802011-01-12 09:06:06 +00003957CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003958 // Push qualifiers into arrays, and then discard any remaining
3959 // qualifiers.
3960 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003961 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003962 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003963 QualType Result;
3964 if (isa<ArrayType>(Ty)) {
3965 Result = getArrayDecayedType(QualType(Ty,0));
3966 } else if (isa<FunctionType>(Ty)) {
3967 Result = getPointerType(QualType(Ty, 0));
3968 } else {
3969 Result = QualType(Ty, 0);
3970 }
3971
3972 return CanQualType::CreateUnsafe(Result);
3973}
3974
John McCall6c9dd522011-01-18 07:41:22 +00003975QualType ASTContext::getUnqualifiedArrayType(QualType type,
3976 Qualifiers &quals) {
3977 SplitQualType splitType = type.getSplitUnqualifiedType();
3978
3979 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3980 // the unqualified desugared type and then drops it on the floor.
3981 // We then have to strip that sugar back off with
3982 // getUnqualifiedDesugaredType(), which is silly.
3983 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003984 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003985
3986 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003987 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003988 quals = splitType.Quals;
3989 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003990 }
3991
John McCall6c9dd522011-01-18 07:41:22 +00003992 // Otherwise, recurse on the array's element type.
3993 QualType elementType = AT->getElementType();
3994 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3995
3996 // If that didn't change the element type, AT has no qualifiers, so we
3997 // can just use the results in splitType.
3998 if (elementType == unqualElementType) {
3999 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004000 quals = splitType.Quals;
4001 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004002 }
4003
4004 // Otherwise, add in the qualifiers from the outermost type, then
4005 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004006 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004007
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004008 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004009 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004010 CAT->getSizeModifier(), 0);
4011 }
4012
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004013 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004014 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004015 }
4016
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004017 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004018 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004019 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004020 VAT->getSizeModifier(),
4021 VAT->getIndexTypeCVRQualifiers(),
4022 VAT->getBracketsRange());
4023 }
4024
4025 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004026 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004027 DSAT->getSizeModifier(), 0,
4028 SourceRange());
4029}
4030
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004031/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4032/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4033/// they point to and return true. If T1 and T2 aren't pointer types
4034/// or pointer-to-member types, or if they are not similar at this
4035/// level, returns false and leaves T1 and T2 unchanged. Top-level
4036/// qualifiers on T1 and T2 are ignored. This function will typically
4037/// be called in a loop that successively "unwraps" pointer and
4038/// pointer-to-member types to compare them at each level.
4039bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4040 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4041 *T2PtrType = T2->getAs<PointerType>();
4042 if (T1PtrType && T2PtrType) {
4043 T1 = T1PtrType->getPointeeType();
4044 T2 = T2PtrType->getPointeeType();
4045 return true;
4046 }
4047
4048 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4049 *T2MPType = T2->getAs<MemberPointerType>();
4050 if (T1MPType && T2MPType &&
4051 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4052 QualType(T2MPType->getClass(), 0))) {
4053 T1 = T1MPType->getPointeeType();
4054 T2 = T2MPType->getPointeeType();
4055 return true;
4056 }
4057
David Blaikiebbafb8a2012-03-11 07:00:24 +00004058 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004059 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4060 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4061 if (T1OPType && T2OPType) {
4062 T1 = T1OPType->getPointeeType();
4063 T2 = T2OPType->getPointeeType();
4064 return true;
4065 }
4066 }
4067
4068 // FIXME: Block pointers, too?
4069
4070 return false;
4071}
4072
Jay Foad39c79802011-01-12 09:06:06 +00004073DeclarationNameInfo
4074ASTContext::getNameForTemplate(TemplateName Name,
4075 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004076 switch (Name.getKind()) {
4077 case TemplateName::QualifiedTemplate:
4078 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004079 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004080 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4081 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004082
John McCalld9dfe3a2011-06-30 08:33:18 +00004083 case TemplateName::OverloadedTemplate: {
4084 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4085 // DNInfo work in progress: CHECKME: what about DNLoc?
4086 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4087 }
4088
4089 case TemplateName::DependentTemplate: {
4090 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004091 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004092 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004093 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4094 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004095 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004096 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4097 // DNInfo work in progress: FIXME: source locations?
4098 DeclarationNameLoc DNLoc;
4099 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4100 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4101 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004102 }
4103 }
4104
John McCalld9dfe3a2011-06-30 08:33:18 +00004105 case TemplateName::SubstTemplateTemplateParm: {
4106 SubstTemplateTemplateParmStorage *subst
4107 = Name.getAsSubstTemplateTemplateParm();
4108 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4109 NameLoc);
4110 }
4111
4112 case TemplateName::SubstTemplateTemplateParmPack: {
4113 SubstTemplateTemplateParmPackStorage *subst
4114 = Name.getAsSubstTemplateTemplateParmPack();
4115 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4116 NameLoc);
4117 }
4118 }
4119
4120 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004121}
4122
Jay Foad39c79802011-01-12 09:06:06 +00004123TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004124 switch (Name.getKind()) {
4125 case TemplateName::QualifiedTemplate:
4126 case TemplateName::Template: {
4127 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004128 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004129 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004130 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4131
4132 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004133 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004134 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004135
John McCalld9dfe3a2011-06-30 08:33:18 +00004136 case TemplateName::OverloadedTemplate:
4137 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004138
John McCalld9dfe3a2011-06-30 08:33:18 +00004139 case TemplateName::DependentTemplate: {
4140 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4141 assert(DTN && "Non-dependent template names must refer to template decls.");
4142 return DTN->CanonicalTemplateName;
4143 }
4144
4145 case TemplateName::SubstTemplateTemplateParm: {
4146 SubstTemplateTemplateParmStorage *subst
4147 = Name.getAsSubstTemplateTemplateParm();
4148 return getCanonicalTemplateName(subst->getReplacement());
4149 }
4150
4151 case TemplateName::SubstTemplateTemplateParmPack: {
4152 SubstTemplateTemplateParmPackStorage *subst
4153 = Name.getAsSubstTemplateTemplateParmPack();
4154 TemplateTemplateParmDecl *canonParameter
4155 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4156 TemplateArgument canonArgPack
4157 = getCanonicalTemplateArgument(subst->getArgumentPack());
4158 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4159 }
4160 }
4161
4162 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004163}
4164
Douglas Gregoradee3e32009-11-11 23:06:43 +00004165bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4166 X = getCanonicalTemplateName(X);
4167 Y = getCanonicalTemplateName(Y);
4168 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4169}
4170
Mike Stump11289f42009-09-09 15:08:12 +00004171TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004172ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004173 switch (Arg.getKind()) {
4174 case TemplateArgument::Null:
4175 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004176
Douglas Gregora8e02e72009-07-28 23:00:59 +00004177 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004178 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004179
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004180 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004181 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004182 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004183 }
Mike Stump11289f42009-09-09 15:08:12 +00004184
Eli Friedmanb826a002012-09-26 02:36:12 +00004185 case TemplateArgument::NullPtr:
4186 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4187 /*isNullPtr*/true);
4188
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004189 case TemplateArgument::Template:
4190 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004191
4192 case TemplateArgument::TemplateExpansion:
4193 return TemplateArgument(getCanonicalTemplateName(
4194 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004195 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004196
Douglas Gregora8e02e72009-07-28 23:00:59 +00004197 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004198 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004199
Douglas Gregora8e02e72009-07-28 23:00:59 +00004200 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004201 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004202
Douglas Gregora8e02e72009-07-28 23:00:59 +00004203 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004204 if (Arg.pack_size() == 0)
4205 return Arg;
4206
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004207 TemplateArgument *CanonArgs
4208 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004209 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004210 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004211 AEnd = Arg.pack_end();
4212 A != AEnd; (void)++A, ++Idx)
4213 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004214
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004215 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004216 }
4217 }
4218
4219 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004220 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004221}
4222
Douglas Gregor333489b2009-03-27 23:10:48 +00004223NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004224ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004225 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004226 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004227
4228 switch (NNS->getKind()) {
4229 case NestedNameSpecifier::Identifier:
4230 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004231 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004232 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4233 NNS->getAsIdentifier());
4234
4235 case NestedNameSpecifier::Namespace:
4236 // A namespace is canonical; build a nested-name-specifier with
4237 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004238 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004239 NNS->getAsNamespace()->getOriginalNamespace());
4240
4241 case NestedNameSpecifier::NamespaceAlias:
4242 // A namespace is canonical; build a nested-name-specifier with
4243 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004244 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004245 NNS->getAsNamespaceAlias()->getNamespace()
4246 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004247
4248 case NestedNameSpecifier::TypeSpec:
4249 case NestedNameSpecifier::TypeSpecWithTemplate: {
4250 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004251
4252 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4253 // break it apart into its prefix and identifier, then reconsititute those
4254 // as the canonical nested-name-specifier. This is required to canonicalize
4255 // a dependent nested-name-specifier involving typedefs of dependent-name
4256 // types, e.g.,
4257 // typedef typename T::type T1;
4258 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004259 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4260 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004261 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004262
Eli Friedman5358a0a2012-03-03 04:09:56 +00004263 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4264 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4265 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004266 return NestedNameSpecifier::Create(*this, nullptr, false,
4267 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004268 }
4269
4270 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004271 case NestedNameSpecifier::Super:
4272 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004273 return NNS;
4274 }
4275
David Blaikie8a40f702012-01-17 06:56:22 +00004276 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004277}
4278
Chris Lattner7adf0762008-08-04 07:31:14 +00004279
Jay Foad39c79802011-01-12 09:06:06 +00004280const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004281 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004282 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004283 // Handle the common positive case fast.
4284 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4285 return AT;
4286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287
John McCall8ccfcb52009-09-24 19:53:00 +00004288 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004289 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004290 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004291
John McCall8ccfcb52009-09-24 19:53:00 +00004292 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004293 // implements C99 6.7.3p8: "If the specification of an array type includes
4294 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004295
Chris Lattner7adf0762008-08-04 07:31:14 +00004296 // If we get here, we either have type qualifiers on the type, or we have
4297 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004298 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004299
John McCall33ddac02011-01-19 10:06:00 +00004300 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004301 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004302
Chris Lattner7adf0762008-08-04 07:31:14 +00004303 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004304 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004305 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004306 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004307
Chris Lattner7adf0762008-08-04 07:31:14 +00004308 // Otherwise, we have an array and we have qualifiers on it. Push the
4309 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004310 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004311
Chris Lattner7adf0762008-08-04 07:31:14 +00004312 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4313 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4314 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004315 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004316 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4317 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4318 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004319 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004320
Mike Stump11289f42009-09-09 15:08:12 +00004321 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004322 = dyn_cast<DependentSizedArrayType>(ATy))
4323 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004324 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004325 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004326 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004327 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004328 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004329
Chris Lattner7adf0762008-08-04 07:31:14 +00004330 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004331 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004332 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004333 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004334 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004335 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004336}
4337
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004338QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004339 if (T->isArrayType() || T->isFunctionType())
4340 return getDecayedType(T);
4341 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004342}
4343
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004344QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004345 T = getVariableArrayDecayedType(T);
4346 T = getAdjustedParameterType(T);
4347 return T.getUnqualifiedType();
4348}
4349
David Majnemerd09a51c2015-03-03 01:50:05 +00004350QualType ASTContext::getExceptionObjectType(QualType T) const {
4351 // C++ [except.throw]p3:
4352 // A throw-expression initializes a temporary object, called the exception
4353 // object, the type of which is determined by removing any top-level
4354 // cv-qualifiers from the static type of the operand of throw and adjusting
4355 // the type from "array of T" or "function returning T" to "pointer to T"
4356 // or "pointer to function returning T", [...]
4357 T = getVariableArrayDecayedType(T);
4358 if (T->isArrayType() || T->isFunctionType())
4359 T = getDecayedType(T);
4360 return T.getUnqualifiedType();
4361}
4362
Chris Lattnera21ad802008-04-02 05:18:44 +00004363/// getArrayDecayedType - Return the properly qualified result of decaying the
4364/// specified array type to a pointer. This operation is non-trivial when
4365/// handling typedefs etc. The canonical type of "T" must be an array type,
4366/// this returns a pointer to a properly qualified element of the array.
4367///
4368/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004369QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004370 // Get the element type with 'getAsArrayType' so that we don't lose any
4371 // typedefs in the element type of the array. This also handles propagation
4372 // of type qualifiers from the array type into the element type if present
4373 // (C99 6.7.3p8).
4374 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4375 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004376
Chris Lattner7adf0762008-08-04 07:31:14 +00004377 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004378
4379 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004380 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004381}
4382
John McCall33ddac02011-01-19 10:06:00 +00004383QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4384 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004385}
4386
John McCall33ddac02011-01-19 10:06:00 +00004387QualType ASTContext::getBaseElementType(QualType type) const {
4388 Qualifiers qs;
4389 while (true) {
4390 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004391 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004392 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004393
John McCall33ddac02011-01-19 10:06:00 +00004394 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004395 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004396 }
Mike Stump11289f42009-09-09 15:08:12 +00004397
John McCall33ddac02011-01-19 10:06:00 +00004398 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004399}
4400
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004401/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004402uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004403ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4404 uint64_t ElementCount = 1;
4405 do {
4406 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004407 CA = dyn_cast_or_null<ConstantArrayType>(
4408 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004409 } while (CA);
4410 return ElementCount;
4411}
4412
Steve Naroff0af91202007-04-27 21:51:21 +00004413/// getFloatingRank - Return a relative rank for floating point types.
4414/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004415static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004416 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004417 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004418
John McCall9dd450b2009-09-21 23:43:11 +00004419 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4420 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004421 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004422 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004423 case BuiltinType::Float: return FloatRank;
4424 case BuiltinType::Double: return DoubleRank;
4425 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004426 }
4427}
4428
Mike Stump11289f42009-09-09 15:08:12 +00004429/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4430/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004431/// 'typeDomain' is a real floating point or complex type.
4432/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004433QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4434 QualType Domain) const {
4435 FloatingRank EltRank = getFloatingRank(Size);
4436 if (Domain->isComplexType()) {
4437 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004438 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004439 case FloatRank: return FloatComplexTy;
4440 case DoubleRank: return DoubleComplexTy;
4441 case LongDoubleRank: return LongDoubleComplexTy;
4442 }
Steve Naroff0af91202007-04-27 21:51:21 +00004443 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004444
4445 assert(Domain->isRealFloatingType() && "Unknown domain!");
4446 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004447 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004448 case FloatRank: return FloatTy;
4449 case DoubleRank: return DoubleTy;
4450 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004451 }
David Blaikief47fa302012-01-17 02:30:50 +00004452 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004453}
4454
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004455/// getFloatingTypeOrder - Compare the rank of the two specified floating
4456/// point types, ignoring the domain of the type (i.e. 'double' ==
4457/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004458/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004459int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004460 FloatingRank LHSR = getFloatingRank(LHS);
4461 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004462
Chris Lattnerb90739d2008-04-06 23:38:49 +00004463 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004464 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004465 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004466 return 1;
4467 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004468}
4469
Chris Lattner76a00cf2008-04-06 22:59:24 +00004470/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4471/// routine will assert if passed a built-in type that isn't an integer or enum,
4472/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004473unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004474 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004475
Chris Lattner76a00cf2008-04-06 22:59:24 +00004476 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004477 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004478 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004479 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004480 case BuiltinType::Char_S:
4481 case BuiltinType::Char_U:
4482 case BuiltinType::SChar:
4483 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004484 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004485 case BuiltinType::Short:
4486 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004487 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004488 case BuiltinType::Int:
4489 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004490 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004491 case BuiltinType::Long:
4492 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004493 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004494 case BuiltinType::LongLong:
4495 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004496 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004497 case BuiltinType::Int128:
4498 case BuiltinType::UInt128:
4499 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004500 }
4501}
4502
Eli Friedman629ffb92009-08-20 04:21:42 +00004503/// \brief Whether this is a promotable bitfield reference according
4504/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4505///
4506/// \returns the type this bit-field will promote to, or NULL if no
4507/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004508QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004509 if (E->isTypeDependent() || E->isValueDependent())
4510 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004511
4512 // FIXME: We should not do this unless E->refersToBitField() is true. This
4513 // matters in C where getSourceBitField() will find bit-fields for various
4514 // cases where the source expression is not a bit-field designator.
4515
John McCalld25db7e2013-05-06 21:39:12 +00004516 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004517 if (!Field)
4518 return QualType();
4519
4520 QualType FT = Field->getType();
4521
Richard Smithcaf33902011-10-10 18:28:20 +00004522 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004523 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004524 // C++ [conv.prom]p5:
4525 // A prvalue for an integral bit-field can be converted to a prvalue of type
4526 // int if int can represent all the values of the bit-field; otherwise, it
4527 // can be converted to unsigned int if unsigned int can represent all the
4528 // values of the bit-field. If the bit-field is larger yet, no integral
4529 // promotion applies to it.
4530 // C11 6.3.1.1/2:
4531 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4532 // If an int can represent all values of the original type (as restricted by
4533 // the width, for a bit-field), the value is converted to an int; otherwise,
4534 // it is converted to an unsigned int.
4535 //
4536 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4537 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004538 if (BitWidth < IntSize)
4539 return IntTy;
4540
4541 if (BitWidth == IntSize)
4542 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4543
4544 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004545 // like the base type. GCC has some weird bugs in this area that we
4546 // deliberately do not follow (GCC follows a pre-standard resolution to
4547 // C's DR315 which treats bit-width as being part of the type, and this leaks
4548 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004549 return QualType();
4550}
4551
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004552/// getPromotedIntegerType - Returns the type that Promotable will
4553/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4554/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004555QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004556 assert(!Promotable.isNull());
4557 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004558 if (const EnumType *ET = Promotable->getAs<EnumType>())
4559 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004560
4561 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4562 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4563 // (3.9.1) can be converted to a prvalue of the first of the following
4564 // types that can represent all the values of its underlying type:
4565 // int, unsigned int, long int, unsigned long int, long long int, or
4566 // unsigned long long int [...]
4567 // FIXME: Is there some better way to compute this?
4568 if (BT->getKind() == BuiltinType::WChar_S ||
4569 BT->getKind() == BuiltinType::WChar_U ||
4570 BT->getKind() == BuiltinType::Char16 ||
4571 BT->getKind() == BuiltinType::Char32) {
4572 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4573 uint64_t FromSize = getTypeSize(BT);
4574 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4575 LongLongTy, UnsignedLongLongTy };
4576 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4577 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4578 if (FromSize < ToSize ||
4579 (FromSize == ToSize &&
4580 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4581 return PromoteTypes[Idx];
4582 }
4583 llvm_unreachable("char type should fit into long long");
4584 }
4585 }
4586
4587 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004588 if (Promotable->isSignedIntegerType())
4589 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004590 uint64_t PromotableSize = getIntWidth(Promotable);
4591 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004592 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4593 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4594}
4595
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004596/// \brief Recurses in pointer/array types until it finds an objc retainable
4597/// type and returns its ownership.
4598Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4599 while (!T.isNull()) {
4600 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4601 return T.getObjCLifetime();
4602 if (T->isArrayType())
4603 T = getBaseElementType(T);
4604 else if (const PointerType *PT = T->getAs<PointerType>())
4605 T = PT->getPointeeType();
4606 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004607 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004608 else
4609 break;
4610 }
4611
4612 return Qualifiers::OCL_None;
4613}
4614
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004615static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4616 // Incomplete enum types are not treated as integer types.
4617 // FIXME: In C++, enum types are never integer types.
4618 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4619 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004620 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004621}
4622
Mike Stump11289f42009-09-09 15:08:12 +00004623/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004624/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004625/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004626int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004627 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4628 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004629
4630 // Unwrap enums to their underlying type.
4631 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4632 LHSC = getIntegerTypeForEnum(ET);
4633 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4634 RHSC = getIntegerTypeForEnum(ET);
4635
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004636 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004637
Chris Lattner76a00cf2008-04-06 22:59:24 +00004638 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4639 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004640
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004641 unsigned LHSRank = getIntegerRank(LHSC);
4642 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004643
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004644 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4645 if (LHSRank == RHSRank) return 0;
4646 return LHSRank > RHSRank ? 1 : -1;
4647 }
Mike Stump11289f42009-09-09 15:08:12 +00004648
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004649 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4650 if (LHSUnsigned) {
4651 // If the unsigned [LHS] type is larger, return it.
4652 if (LHSRank >= RHSRank)
4653 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004654
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004655 // If the signed type can represent all values of the unsigned type, it
4656 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004657 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004658 return -1;
4659 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004660
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004661 // If the unsigned [RHS] type is larger, return it.
4662 if (RHSRank >= LHSRank)
4663 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004664
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004665 // If the signed type can represent all values of the unsigned type, it
4666 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004667 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004668 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004669}
Anders Carlsson98f07902007-08-17 05:31:46 +00004670
Mike Stump11289f42009-09-09 15:08:12 +00004671// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004672QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004673 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004674 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004675 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004676
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004677 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004678
Anders Carlsson98f07902007-08-17 05:31:46 +00004679 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004680 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004681 // int flags;
4682 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004683 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004684 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004685 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004686 FieldTypes[3] = LongTy;
4687
Anders Carlsson98f07902007-08-17 05:31:46 +00004688 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004689 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004690 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004691 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004692 SourceLocation(), nullptr,
4693 FieldTypes[i], /*TInfo=*/nullptr,
4694 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004695 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004696 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004697 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004698 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004699 }
4700
Douglas Gregord5058122010-02-11 01:19:42 +00004701 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004702 }
Mike Stump11289f42009-09-09 15:08:12 +00004703
Anders Carlsson98f07902007-08-17 05:31:46 +00004704 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004705}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004706
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004707QualType ASTContext::getObjCSuperType() const {
4708 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004709 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004710 TUDecl->addDecl(ObjCSuperTypeDecl);
4711 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4712 }
4713 return ObjCSuperType;
4714}
4715
Douglas Gregor512b0772009-04-23 22:29:11 +00004716void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004717 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004718 assert(Rec && "Invalid CFConstantStringType");
4719 CFConstantStringTypeDecl = Rec->getDecl();
4720}
4721
Jay Foad39c79802011-01-12 09:06:06 +00004722QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004723 if (BlockDescriptorType)
4724 return getTagDeclType(BlockDescriptorType);
4725
Alp Toker2dea15b2013-12-17 01:22:38 +00004726 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004727 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004728 RD = buildImplicitRecord("__block_descriptor");
4729 RD->startDefinition();
4730
Mike Stumpd0153282009-10-20 02:12:22 +00004731 QualType FieldTypes[] = {
4732 UnsignedLongTy,
4733 UnsignedLongTy,
4734 };
4735
Craig Topperd6d31ac2013-07-15 08:24:27 +00004736 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004737 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004738 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004739 };
4740
4741 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004742 FieldDecl *Field = FieldDecl::Create(
4743 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004744 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4745 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004746 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004747 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004748 }
4749
Alp Toker2dea15b2013-12-17 01:22:38 +00004750 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004751
Alp Toker2dea15b2013-12-17 01:22:38 +00004752 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004753
4754 return getTagDeclType(BlockDescriptorType);
4755}
4756
Jay Foad39c79802011-01-12 09:06:06 +00004757QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004758 if (BlockDescriptorExtendedType)
4759 return getTagDeclType(BlockDescriptorExtendedType);
4760
Alp Toker2dea15b2013-12-17 01:22:38 +00004761 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004762 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004763 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4764 RD->startDefinition();
4765
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004766 QualType FieldTypes[] = {
4767 UnsignedLongTy,
4768 UnsignedLongTy,
4769 getPointerType(VoidPtrTy),
4770 getPointerType(VoidPtrTy)
4771 };
4772
Craig Topperd6d31ac2013-07-15 08:24:27 +00004773 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004774 "reserved",
4775 "Size",
4776 "CopyFuncPtr",
4777 "DestroyFuncPtr"
4778 };
4779
4780 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004781 FieldDecl *Field = FieldDecl::Create(
4782 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004783 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4784 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004785 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004786 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004787 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004788 }
4789
Alp Toker2dea15b2013-12-17 01:22:38 +00004790 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004791
Alp Toker2dea15b2013-12-17 01:22:38 +00004792 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004793 return getTagDeclType(BlockDescriptorExtendedType);
4794}
4795
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004796/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4797/// requires copy/dispose. Note that this must match the logic
4798/// in buildByrefHelpers.
4799bool ASTContext::BlockRequiresCopying(QualType Ty,
4800 const VarDecl *D) {
4801 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4802 const Expr *copyExpr = getBlockVarCopyInits(D);
4803 if (!copyExpr && record->hasTrivialDestructor()) return false;
4804
Mike Stump94967902009-10-21 18:16:27 +00004805 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004806 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004807
4808 if (!Ty->isObjCRetainableType()) return false;
4809
4810 Qualifiers qs = Ty.getQualifiers();
4811
4812 // If we have lifetime, that dominates.
4813 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4814 assert(getLangOpts().ObjCAutoRefCount);
4815
4816 switch (lifetime) {
4817 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4818
4819 // These are just bits as far as the runtime is concerned.
4820 case Qualifiers::OCL_ExplicitNone:
4821 case Qualifiers::OCL_Autoreleasing:
4822 return false;
4823
4824 // Tell the runtime that this is ARC __weak, called by the
4825 // byref routines.
4826 case Qualifiers::OCL_Weak:
4827 // ARC __strong __block variables need to be retained.
4828 case Qualifiers::OCL_Strong:
4829 return true;
4830 }
4831 llvm_unreachable("fell out of lifetime switch!");
4832 }
4833 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4834 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004835}
4836
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004837bool ASTContext::getByrefLifetime(QualType Ty,
4838 Qualifiers::ObjCLifetime &LifeTime,
4839 bool &HasByrefExtendedLayout) const {
4840
4841 if (!getLangOpts().ObjC1 ||
4842 getLangOpts().getGC() != LangOptions::NonGC)
4843 return false;
4844
4845 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004846 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004847 HasByrefExtendedLayout = true;
4848 LifeTime = Qualifiers::OCL_None;
4849 }
4850 else if (getLangOpts().ObjCAutoRefCount)
4851 LifeTime = Ty.getObjCLifetime();
4852 // MRR.
4853 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4854 LifeTime = Qualifiers::OCL_ExplicitNone;
4855 else
4856 LifeTime = Qualifiers::OCL_None;
4857 return true;
4858}
4859
Douglas Gregorbab8a962011-09-08 01:46:34 +00004860TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4861 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004862 ObjCInstanceTypeDecl =
4863 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004864 return ObjCInstanceTypeDecl;
4865}
4866
Anders Carlsson18acd442007-10-29 06:33:42 +00004867// This returns true if a type has been typedefed to BOOL:
4868// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004869static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004870 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004871 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4872 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004873
Anders Carlssond8499822007-10-29 05:01:08 +00004874 return false;
4875}
4876
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004877/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004878/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004879CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004880 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4881 return CharUnits::Zero();
4882
Ken Dyck40775002010-01-11 17:06:35 +00004883 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004884
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004885 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004886 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004887 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004888 // Treat arrays as pointers, since that's how they're passed in.
4889 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004890 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004891 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004892}
4893
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004894bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4895 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4896 VD->getType()->isIntegralOrEnumerationType() &&
4897 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4898}
4899
Ken Dyck40775002010-01-11 17:06:35 +00004900static inline
4901std::string charUnitsToString(const CharUnits &CU) {
4902 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004903}
4904
John McCall351762c2011-02-07 10:33:21 +00004905/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004906/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004907std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4908 std::string S;
4909
David Chisnall950a9512009-11-17 19:33:30 +00004910 const BlockDecl *Decl = Expr->getBlockDecl();
4911 QualType BlockTy =
4912 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4913 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004914 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004915 getObjCEncodingForMethodParameter(
4916 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4917 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004918 else
Alp Toker314cc812014-01-25 16:55:45 +00004919 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004920 // Compute size of all parameters.
4921 // Start with computing size of a pointer in number of bytes.
4922 // FIXME: There might(should) be a better way of doing this computation!
4923 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004924 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4925 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004926 for (auto PI : Decl->params()) {
4927 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004928 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004929 if (sz.isZero())
4930 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004931 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004932 ParmOffset += sz;
4933 }
4934 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004935 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004936 // Block pointer and offset.
4937 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004938
4939 // Argument types.
4940 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004941 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004942 QualType PType = PVDecl->getOriginalType();
4943 if (const ArrayType *AT =
4944 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4945 // Use array's original type only if it has known number of
4946 // elements.
4947 if (!isa<ConstantArrayType>(AT))
4948 PType = PVDecl->getType();
4949 } else if (PType->isFunctionType())
4950 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004951 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004952 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4953 S, true /*Extended*/);
4954 else
4955 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004956 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004957 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004958 }
John McCall351762c2011-02-07 10:33:21 +00004959
4960 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004961}
4962
Douglas Gregora9d84932011-05-27 01:19:52 +00004963bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004964 std::string& S) {
4965 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004966 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004967 CharUnits ParmOffset;
4968 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004969 for (auto PI : Decl->params()) {
4970 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004971 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004972 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004973 continue;
4974
David Chisnall50e4eba2010-12-30 14:05:53 +00004975 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004976 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004977 ParmOffset += sz;
4978 }
4979 S += charUnitsToString(ParmOffset);
4980 ParmOffset = CharUnits::Zero();
4981
4982 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004983 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004984 QualType PType = PVDecl->getOriginalType();
4985 if (const ArrayType *AT =
4986 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4987 // Use array's original type only if it has known number of
4988 // elements.
4989 if (!isa<ConstantArrayType>(AT))
4990 PType = PVDecl->getType();
4991 } else if (PType->isFunctionType())
4992 PType = PVDecl->getType();
4993 getObjCEncodingForType(PType, S);
4994 S += charUnitsToString(ParmOffset);
4995 ParmOffset += getObjCEncodingTypeSize(PType);
4996 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004997
4998 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004999}
5000
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005001/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5002/// method parameter or return type. If Extended, include class names and
5003/// block object types.
5004void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5005 QualType T, std::string& S,
5006 bool Extended) const {
5007 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5008 getObjCEncodingForTypeQualifier(QT, S);
5009 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005010 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005011 true /*OutermostType*/,
5012 false /*EncodingProperty*/,
5013 false /*StructField*/,
5014 Extended /*EncodeBlockParameters*/,
5015 Extended /*EncodeClassNames*/);
5016}
5017
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005018/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005019/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005020bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005021 std::string& S,
5022 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005023 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005024 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005025 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5026 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005027 // Compute size of all parameters.
5028 // Start with computing size of a pointer in number of bytes.
5029 // FIXME: There might(should) be a better way of doing this computation!
5030 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005031 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005032 // The first two arguments (self and _cmd) are pointers; account for
5033 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005034 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005035 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005036 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005037 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005038 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005039 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005040 continue;
5041
Ken Dyck40775002010-01-11 17:06:35 +00005042 assert (sz.isPositive() &&
5043 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005044 ParmOffset += sz;
5045 }
Ken Dyck40775002010-01-11 17:06:35 +00005046 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005047 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005048 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005049
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005050 // Argument types.
5051 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005052 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005053 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005054 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005055 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005056 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005057 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5058 // Use array's original type only if it has known number of
5059 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005060 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005061 PType = PVDecl->getType();
5062 } else if (PType->isFunctionType())
5063 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005064 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5065 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005066 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005067 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005068 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005069
5070 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005071}
5072
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005073ObjCPropertyImplDecl *
5074ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5075 const ObjCPropertyDecl *PD,
5076 const Decl *Container) const {
5077 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005078 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005079 if (const ObjCCategoryImplDecl *CID =
5080 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005081 for (auto *PID : CID->property_impls())
5082 if (PID->getPropertyDecl() == PD)
5083 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005084 } else {
5085 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5086 for (auto *PID : OID->property_impls())
5087 if (PID->getPropertyDecl() == PD)
5088 return PID;
5089 }
5090 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005091}
5092
Daniel Dunbar4932b362008-08-28 04:38:10 +00005093/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005094/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005095/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5096/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005097/// Property attributes are stored as a comma-delimited C string. The simple
5098/// attributes readonly and bycopy are encoded as single characters. The
5099/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5100/// encoded as single characters, followed by an identifier. Property types
5101/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005102/// these attributes are defined by the following enumeration:
5103/// @code
5104/// enum PropertyAttributes {
5105/// kPropertyReadOnly = 'R', // property is read-only.
5106/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5107/// kPropertyByref = '&', // property is a reference to the value last assigned
5108/// kPropertyDynamic = 'D', // property is dynamic
5109/// kPropertyGetter = 'G', // followed by getter selector name
5110/// kPropertySetter = 'S', // followed by setter selector name
5111/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005112/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005113/// kPropertyWeak = 'W' // 'weak' property
5114/// kPropertyStrong = 'P' // property GC'able
5115/// kPropertyNonAtomic = 'N' // property non-atomic
5116/// };
5117/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005118void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005119 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005120 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005121 // Collect information from the property implementation decl(s).
5122 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005123 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005124
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005125 if (ObjCPropertyImplDecl *PropertyImpDecl =
5126 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5127 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5128 Dynamic = true;
5129 else
5130 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005131 }
5132
5133 // FIXME: This is not very efficient.
5134 S = "T";
5135
5136 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005137 // GCC has some special rules regarding encoding of properties which
5138 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005139 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005140
5141 if (PD->isReadOnly()) {
5142 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005143 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5144 S += ",C";
5145 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5146 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005147 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5148 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005149 } else {
5150 switch (PD->getSetterKind()) {
5151 case ObjCPropertyDecl::Assign: break;
5152 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005153 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005154 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005155 }
5156 }
5157
5158 // It really isn't clear at all what this means, since properties
5159 // are "dynamic by default".
5160 if (Dynamic)
5161 S += ",D";
5162
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005163 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5164 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005165
Daniel Dunbar4932b362008-08-28 04:38:10 +00005166 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5167 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005168 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005169 }
5170
5171 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5172 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005173 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005174 }
5175
5176 if (SynthesizePID) {
5177 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5178 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005179 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005180 }
5181
5182 // FIXME: OBJCGC: weak & strong
5183}
5184
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005185/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005186/// Another legacy compatibility encoding: 32-bit longs are encoded as
5187/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005188/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5189///
5190void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005191 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005192 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005193 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005194 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005195 else
Jay Foad39c79802011-01-12 09:06:06 +00005196 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005197 PointeeTy = IntTy;
5198 }
5199 }
5200}
5201
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005202void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005203 const FieldDecl *Field,
5204 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005205 // We follow the behavior of gcc, expanding structures which are
5206 // directly pointed to, and expanding embedded structures. Note that
5207 // these rules are sufficient to prevent recursive encoding of the
5208 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005209 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005210 true /* outermost type */, false, false,
5211 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005212}
5213
Joe Groff98ac7d22014-07-07 22:25:15 +00005214void ASTContext::getObjCEncodingForPropertyType(QualType T,
5215 std::string& S) const {
5216 // Encode result type.
5217 // GCC has some special rules regarding encoding of properties which
5218 // closely resembles encoding of ivars.
5219 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5220 true /* outermost type */,
5221 true /* encoding property */);
5222}
5223
John McCall393a78d2012-12-20 02:45:14 +00005224static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5225 BuiltinType::Kind kind) {
5226 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005227 case BuiltinType::Void: return 'v';
5228 case BuiltinType::Bool: return 'B';
5229 case BuiltinType::Char_U:
5230 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005231 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005232 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005233 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005234 case BuiltinType::UInt: return 'I';
5235 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005236 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005237 case BuiltinType::UInt128: return 'T';
5238 case BuiltinType::ULongLong: return 'Q';
5239 case BuiltinType::Char_S:
5240 case BuiltinType::SChar: return 'c';
5241 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005242 case BuiltinType::WChar_S:
5243 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005244 case BuiltinType::Int: return 'i';
5245 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005246 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005247 case BuiltinType::LongLong: return 'q';
5248 case BuiltinType::Int128: return 't';
5249 case BuiltinType::Float: return 'f';
5250 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005251 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005252 case BuiltinType::NullPtr: return '*'; // like char*
5253
5254 case BuiltinType::Half:
5255 // FIXME: potentially need @encodes for these!
5256 return ' ';
5257
5258 case BuiltinType::ObjCId:
5259 case BuiltinType::ObjCClass:
5260 case BuiltinType::ObjCSel:
5261 llvm_unreachable("@encoding ObjC primitive type");
5262
5263 // OpenCL and placeholder types don't need @encodings.
5264 case BuiltinType::OCLImage1d:
5265 case BuiltinType::OCLImage1dArray:
5266 case BuiltinType::OCLImage1dBuffer:
5267 case BuiltinType::OCLImage2d:
5268 case BuiltinType::OCLImage2dArray:
5269 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005270 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005271 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005272 case BuiltinType::Dependent:
5273#define BUILTIN_TYPE(KIND, ID)
5274#define PLACEHOLDER_TYPE(KIND, ID) \
5275 case BuiltinType::KIND:
5276#include "clang/AST/BuiltinTypes.def"
5277 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005278 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005279 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005280}
5281
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005282static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5283 EnumDecl *Enum = ET->getDecl();
5284
5285 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5286 if (!Enum->isFixed())
5287 return 'i';
5288
5289 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005290 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5291 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005292}
5293
Jay Foad39c79802011-01-12 09:06:06 +00005294static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005295 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005296 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005297 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005298 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5299 // The GNU runtime requires more information; bitfields are encoded as b,
5300 // then the offset (in bits) of the first element, then the type of the
5301 // bitfield, then the size in bits. For example, in this structure:
5302 //
5303 // struct
5304 // {
5305 // int integer;
5306 // int flags:2;
5307 // };
5308 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5309 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5310 // information is not especially sensible, but we're stuck with it for
5311 // compatibility with GCC, although providing it breaks anything that
5312 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005313 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005314 const RecordDecl *RD = FD->getParent();
5315 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005316 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005317 if (const EnumType *ET = T->getAs<EnumType>())
5318 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005319 else {
5320 const BuiltinType *BT = T->castAs<BuiltinType>();
5321 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5322 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005323 }
Richard Smithcaf33902011-10-10 18:28:20 +00005324 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005325}
5326
Daniel Dunbar07d07852009-10-18 21:17:35 +00005327// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005328void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5329 bool ExpandPointedToStructures,
5330 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005331 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005332 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005333 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005334 bool StructField,
5335 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005336 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005337 bool EncodePointerToObjCTypedef,
5338 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005339 CanQualType CT = getCanonicalType(T);
5340 switch (CT->getTypeClass()) {
5341 case Type::Builtin:
5342 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005343 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005344 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005345 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5346 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5347 else
5348 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005349 return;
Mike Stump11289f42009-09-09 15:08:12 +00005350
John McCall393a78d2012-12-20 02:45:14 +00005351 case Type::Complex: {
5352 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005353 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005354 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005355 return;
5356 }
John McCall393a78d2012-12-20 02:45:14 +00005357
5358 case Type::Atomic: {
5359 const AtomicType *AT = T->castAs<AtomicType>();
5360 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005361 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005362 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005363 }
John McCall393a78d2012-12-20 02:45:14 +00005364
5365 // encoding for pointer or reference types.
5366 case Type::Pointer:
5367 case Type::LValueReference:
5368 case Type::RValueReference: {
5369 QualType PointeeTy;
5370 if (isa<PointerType>(CT)) {
5371 const PointerType *PT = T->castAs<PointerType>();
5372 if (PT->isObjCSelType()) {
5373 S += ':';
5374 return;
5375 }
5376 PointeeTy = PT->getPointeeType();
5377 } else {
5378 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5379 }
5380
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005381 bool isReadOnly = false;
5382 // For historical/compatibility reasons, the read-only qualifier of the
5383 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5384 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005385 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005386 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005387 if (OutermostType && T.isConstQualified()) {
5388 isReadOnly = true;
5389 S += 'r';
5390 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005391 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005392 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005393 while (P->getAs<PointerType>())
5394 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005395 if (P.isConstQualified()) {
5396 isReadOnly = true;
5397 S += 'r';
5398 }
5399 }
5400 if (isReadOnly) {
5401 // Another legacy compatibility encoding. Some ObjC qualifier and type
5402 // combinations need to be rearranged.
5403 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005404 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005405 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005406 }
Mike Stump11289f42009-09-09 15:08:12 +00005407
Anders Carlssond8499822007-10-29 05:01:08 +00005408 if (PointeeTy->isCharType()) {
5409 // char pointer types should be encoded as '*' unless it is a
5410 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005411 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005412 S += '*';
5413 return;
5414 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005415 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005416 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5417 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5418 S += '#';
5419 return;
5420 }
5421 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5422 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5423 S += '@';
5424 return;
5425 }
5426 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005427 }
Anders Carlssond8499822007-10-29 05:01:08 +00005428 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005429 getLegacyIntegralTypeEncoding(PointeeTy);
5430
Mike Stump11289f42009-09-09 15:08:12 +00005431 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005432 nullptr, false, false, false, false, false, false,
5433 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005434 return;
5435 }
John McCall393a78d2012-12-20 02:45:14 +00005436
5437 case Type::ConstantArray:
5438 case Type::IncompleteArray:
5439 case Type::VariableArray: {
5440 const ArrayType *AT = cast<ArrayType>(CT);
5441
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005442 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005443 // Incomplete arrays are encoded as a pointer to the array element.
5444 S += '^';
5445
Mike Stump11289f42009-09-09 15:08:12 +00005446 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005447 false, ExpandStructures, FD);
5448 } else {
5449 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005450
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005451 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5452 S += llvm::utostr(CAT->getSize().getZExtValue());
5453 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005454 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005455 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5456 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005457 S += '0';
5458 }
Mike Stump11289f42009-09-09 15:08:12 +00005459
5460 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005461 false, ExpandStructures, FD,
5462 false, false, false, false, false, false,
5463 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005464 S += ']';
5465 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005466 return;
5467 }
Mike Stump11289f42009-09-09 15:08:12 +00005468
John McCall393a78d2012-12-20 02:45:14 +00005469 case Type::FunctionNoProto:
5470 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005471 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005472 return;
Mike Stump11289f42009-09-09 15:08:12 +00005473
John McCall393a78d2012-12-20 02:45:14 +00005474 case Type::Record: {
5475 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005476 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005477 // Anonymous structures print as '?'
5478 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5479 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005480 if (ClassTemplateSpecializationDecl *Spec
5481 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5482 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005483 llvm::raw_string_ostream OS(S);
5484 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005485 TemplateArgs.data(),
5486 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005487 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005488 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005489 } else {
5490 S += '?';
5491 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005492 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005493 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005494 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005495 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005496 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005497 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005498 if (FD) {
5499 S += '"';
5500 S += Field->getNameAsString();
5501 S += '"';
5502 }
Mike Stump11289f42009-09-09 15:08:12 +00005503
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005504 // Special case bit-fields.
5505 if (Field->isBitField()) {
5506 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005507 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005508 } else {
5509 QualType qt = Field->getType();
5510 getLegacyIntegralTypeEncoding(qt);
5511 getObjCEncodingForTypeImpl(qt, S, false, true,
5512 FD, /*OutermostType*/false,
5513 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005514 /*StructField*/true,
5515 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005516 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005517 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005518 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005519 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005520 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005521 return;
5522 }
Mike Stump11289f42009-09-09 15:08:12 +00005523
John McCall393a78d2012-12-20 02:45:14 +00005524 case Type::BlockPointer: {
5525 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005526 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005527 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005528 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005529
5530 S += '<';
5531 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005532 getObjCEncodingForTypeImpl(
5533 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5534 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005535 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5536 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005537 // Block self
5538 S += "@?";
5539 // Block parameters
5540 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005541 for (const auto &I : FPT->param_types())
5542 getObjCEncodingForTypeImpl(
5543 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5544 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005545 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5546 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005547 }
5548 S += '>';
5549 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005550 return;
5551 }
Mike Stump11289f42009-09-09 15:08:12 +00005552
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005553 case Type::ObjCObject: {
5554 // hack to match legacy encoding of *id and *Class
5555 QualType Ty = getObjCObjectPointerType(CT);
5556 if (Ty->isObjCIdType()) {
5557 S += "{objc_object=}";
5558 return;
5559 }
5560 else if (Ty->isObjCClassType()) {
5561 S += "{objc_class=}";
5562 return;
5563 }
5564 }
5565
John McCall393a78d2012-12-20 02:45:14 +00005566 case Type::ObjCInterface: {
5567 // Ignore protocol qualifiers when mangling at this level.
5568 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005569
John McCall393a78d2012-12-20 02:45:14 +00005570 // The assumption seems to be that this assert will succeed
5571 // because nested levels will have filtered out 'id' and 'Class'.
5572 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005573 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005574 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005575 S += '{';
5576 const IdentifierInfo *II = OI->getIdentifier();
5577 S += II->getName();
5578 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005579 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005580 DeepCollectObjCIvars(OI, true, Ivars);
5581 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005582 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005583 if (Field->isBitField())
5584 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005585 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005586 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5587 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005588 EncodePointerToObjCTypedef,
5589 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005590 }
5591 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005592 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005593 }
Mike Stump11289f42009-09-09 15:08:12 +00005594
John McCall393a78d2012-12-20 02:45:14 +00005595 case Type::ObjCObjectPointer: {
5596 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005597 if (OPT->isObjCIdType()) {
5598 S += '@';
5599 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005600 }
Mike Stump11289f42009-09-09 15:08:12 +00005601
Steve Narofff0c86112009-10-28 22:03:49 +00005602 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5603 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5604 // Since this is a binary compatibility issue, need to consult with runtime
5605 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005606 S += '#';
5607 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005608 }
Mike Stump11289f42009-09-09 15:08:12 +00005609
Chris Lattnere7cabb92009-07-13 00:10:46 +00005610 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005611 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005612 ExpandPointedToStructures,
5613 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005614 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005615 // Note that we do extended encoding of protocol qualifer list
5616 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005617 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005618 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005619 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005620 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005621 S += '>';
5622 }
5623 S += '"';
5624 }
5625 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005626 }
Mike Stump11289f42009-09-09 15:08:12 +00005627
Chris Lattnere7cabb92009-07-13 00:10:46 +00005628 QualType PointeeTy = OPT->getPointeeType();
5629 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005630 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5631 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005632 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005633 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005634 // {...};
5635 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005636 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005637 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005638 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5639 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5640 DeepCollectObjCIvars(OI, true, Ivars);
5641 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5642 if (cast<FieldDecl>(Ivars[i]) == FD) {
5643 S += '{';
5644 S += OI->getIdentifier()->getName();
5645 S += '}';
5646 return;
5647 }
5648 }
5649 }
Mike Stump11289f42009-09-09 15:08:12 +00005650 getObjCEncodingForTypeImpl(PointeeTy, S,
5651 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005652 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005653 false, false, false, false, false,
5654 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005655 return;
5656 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005657
5658 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005659 if (OPT->getInterfaceDecl() &&
5660 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005661 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005662 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005663 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005664 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005665 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005666 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005667 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005668 S += '"';
5669 }
5670 return;
5671 }
Mike Stump11289f42009-09-09 15:08:12 +00005672
John McCalla9e6e8d2010-05-17 23:56:34 +00005673 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005674 // FIXME: we shoul do better than that. 'M' is available.
5675 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005676 // This matches gcc's encoding, even though technically it is insufficient.
5677 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005678 case Type::Vector:
5679 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005680 // Until we have a coherent encoding of these three types, issue warning.
5681 { if (NotEncodedT)
5682 *NotEncodedT = T;
5683 return;
5684 }
5685
5686 // We could see an undeduced auto type here during error recovery.
5687 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005688 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005689 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005690
Richard Smith27d807c2013-04-30 13:56:41 +00005691
John McCall393a78d2012-12-20 02:45:14 +00005692#define ABSTRACT_TYPE(KIND, BASE)
5693#define TYPE(KIND, BASE)
5694#define DEPENDENT_TYPE(KIND, BASE) \
5695 case Type::KIND:
5696#define NON_CANONICAL_TYPE(KIND, BASE) \
5697 case Type::KIND:
5698#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5699 case Type::KIND:
5700#include "clang/AST/TypeNodes.def"
5701 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005702 }
John McCall393a78d2012-12-20 02:45:14 +00005703 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005704}
5705
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005706void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5707 std::string &S,
5708 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005709 bool includeVBases,
5710 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005711 assert(RDecl && "Expected non-null RecordDecl");
5712 assert(!RDecl->isUnion() && "Should not be called for unions");
5713 if (!RDecl->getDefinition())
5714 return;
5715
5716 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5717 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5718 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5719
5720 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005721 for (const auto &BI : CXXRec->bases()) {
5722 if (!BI.isVirtual()) {
5723 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005724 if (base->isEmpty())
5725 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005726 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005727 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5728 std::make_pair(offs, base));
5729 }
5730 }
5731 }
5732
5733 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005734 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005735 uint64_t offs = layout.getFieldOffset(i);
5736 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005737 std::make_pair(offs, Field));
5738 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005739 }
5740
5741 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005742 for (const auto &BI : CXXRec->vbases()) {
5743 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005744 if (base->isEmpty())
5745 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005746 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005747 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5748 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005749 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5750 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005751 }
5752 }
5753
5754 CharUnits size;
5755 if (CXXRec) {
5756 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5757 } else {
5758 size = layout.getSize();
5759 }
5760
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005761#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005762 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005763#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005764 std::multimap<uint64_t, NamedDecl *>::iterator
5765 CurLayObj = FieldOrBaseOffsets.begin();
5766
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005767 if (CXXRec && CXXRec->isDynamicClass() &&
5768 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005769 if (FD) {
5770 S += "\"_vptr$";
5771 std::string recname = CXXRec->getNameAsString();
5772 if (recname.empty()) recname = "?";
5773 S += recname;
5774 S += '"';
5775 }
5776 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005777#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005778 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005779#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005780 }
5781
5782 if (!RDecl->hasFlexibleArrayMember()) {
5783 // Mark the end of the structure.
5784 uint64_t offs = toBits(size);
5785 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005786 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005787 }
5788
5789 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005790#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005791 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005792 if (CurOffs < CurLayObj->first) {
5793 uint64_t padding = CurLayObj->first - CurOffs;
5794 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5795 // packing/alignment of members is different that normal, in which case
5796 // the encoding will be out-of-sync with the real layout.
5797 // If the runtime switches to just consider the size of types without
5798 // taking into account alignment, we could make padding explicit in the
5799 // encoding (e.g. using arrays of chars). The encoding strings would be
5800 // longer then though.
5801 CurOffs += padding;
5802 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005803#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005804
5805 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005806 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005807 break; // reached end of structure.
5808
5809 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5810 // We expand the bases without their virtual bases since those are going
5811 // in the initial structure. Note that this differs from gcc which
5812 // expands virtual bases each time one is encountered in the hierarchy,
5813 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005814 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5815 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005816 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005817#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005818 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005819#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005820 } else {
5821 FieldDecl *field = cast<FieldDecl>(dcl);
5822 if (FD) {
5823 S += '"';
5824 S += field->getNameAsString();
5825 S += '"';
5826 }
5827
5828 if (field->isBitField()) {
5829 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005830#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005831 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005832#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005833 } else {
5834 QualType qt = field->getType();
5835 getLegacyIntegralTypeEncoding(qt);
5836 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5837 /*OutermostType*/false,
5838 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005839 /*StructField*/true,
5840 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005841#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005842 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005843#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005844 }
5845 }
5846 }
5847}
5848
Mike Stump11289f42009-09-09 15:08:12 +00005849void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005850 std::string& S) const {
5851 if (QT & Decl::OBJC_TQ_In)
5852 S += 'n';
5853 if (QT & Decl::OBJC_TQ_Inout)
5854 S += 'N';
5855 if (QT & Decl::OBJC_TQ_Out)
5856 S += 'o';
5857 if (QT & Decl::OBJC_TQ_Bycopy)
5858 S += 'O';
5859 if (QT & Decl::OBJC_TQ_Byref)
5860 S += 'R';
5861 if (QT & Decl::OBJC_TQ_Oneway)
5862 S += 'V';
5863}
5864
Douglas Gregor3ea72692011-08-12 05:46:01 +00005865TypedefDecl *ASTContext::getObjCIdDecl() const {
5866 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005867 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005868 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005869 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005870 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005871 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005872}
5873
Douglas Gregor52e02802011-08-12 06:17:30 +00005874TypedefDecl *ASTContext::getObjCSelDecl() const {
5875 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005876 QualType T = getPointerType(ObjCBuiltinSelTy);
5877 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005878 }
5879 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005880}
5881
Douglas Gregor0a586182011-08-12 05:59:41 +00005882TypedefDecl *ASTContext::getObjCClassDecl() const {
5883 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005884 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005885 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005886 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005887 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005888 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005889}
5890
Douglas Gregord53ae832012-01-17 18:09:05 +00005891ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5892 if (!ObjCProtocolClassDecl) {
5893 ObjCProtocolClassDecl
5894 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5895 SourceLocation(),
5896 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005897 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005898 SourceLocation(), true);
5899 }
5900
5901 return ObjCProtocolClassDecl;
5902}
5903
Meador Inge5d3fb222012-06-16 03:34:49 +00005904//===----------------------------------------------------------------------===//
5905// __builtin_va_list Construction Functions
5906//===----------------------------------------------------------------------===//
5907
5908static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5909 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005910 QualType T = Context->getPointerType(Context->CharTy);
5911 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005912}
5913
5914static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5915 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005916 QualType T = Context->getPointerType(Context->VoidTy);
5917 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005918}
5919
Tim Northover9bb857a2013-01-31 12:13:10 +00005920static TypedefDecl *
5921CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005922 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005923 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005924 if (Context->getLangOpts().CPlusPlus) {
5925 // namespace std { struct __va_list {
5926 NamespaceDecl *NS;
5927 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5928 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005929 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005930 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005931 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005932 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005933 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005934 }
5935
5936 VaListTagDecl->startDefinition();
5937
5938 const size_t NumFields = 5;
5939 QualType FieldTypes[NumFields];
5940 const char *FieldNames[NumFields];
5941
5942 // void *__stack;
5943 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5944 FieldNames[0] = "__stack";
5945
5946 // void *__gr_top;
5947 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5948 FieldNames[1] = "__gr_top";
5949
5950 // void *__vr_top;
5951 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5952 FieldNames[2] = "__vr_top";
5953
5954 // int __gr_offs;
5955 FieldTypes[3] = Context->IntTy;
5956 FieldNames[3] = "__gr_offs";
5957
5958 // int __vr_offs;
5959 FieldTypes[4] = Context->IntTy;
5960 FieldNames[4] = "__vr_offs";
5961
5962 // Create fields
5963 for (unsigned i = 0; i < NumFields; ++i) {
5964 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5965 VaListTagDecl,
5966 SourceLocation(),
5967 SourceLocation(),
5968 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005969 FieldTypes[i], /*TInfo=*/nullptr,
5970 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005971 /*Mutable=*/false,
5972 ICIS_NoInit);
5973 Field->setAccess(AS_public);
5974 VaListTagDecl->addDecl(Field);
5975 }
5976 VaListTagDecl->completeDefinition();
5977 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5978 Context->VaListTagTy = VaListTagType;
5979
5980 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005981 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005982}
5983
Meador Inge5d3fb222012-06-16 03:34:49 +00005984static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5985 // typedef struct __va_list_tag {
5986 RecordDecl *VaListTagDecl;
5987
Alp Toker2dea15b2013-12-17 01:22:38 +00005988 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005989 VaListTagDecl->startDefinition();
5990
5991 const size_t NumFields = 5;
5992 QualType FieldTypes[NumFields];
5993 const char *FieldNames[NumFields];
5994
5995 // unsigned char gpr;
5996 FieldTypes[0] = Context->UnsignedCharTy;
5997 FieldNames[0] = "gpr";
5998
5999 // unsigned char fpr;
6000 FieldTypes[1] = Context->UnsignedCharTy;
6001 FieldNames[1] = "fpr";
6002
6003 // unsigned short reserved;
6004 FieldTypes[2] = Context->UnsignedShortTy;
6005 FieldNames[2] = "reserved";
6006
6007 // void* overflow_arg_area;
6008 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6009 FieldNames[3] = "overflow_arg_area";
6010
6011 // void* reg_save_area;
6012 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6013 FieldNames[4] = "reg_save_area";
6014
6015 // Create fields
6016 for (unsigned i = 0; i < NumFields; ++i) {
6017 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6018 SourceLocation(),
6019 SourceLocation(),
6020 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006021 FieldTypes[i], /*TInfo=*/nullptr,
6022 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006023 /*Mutable=*/false,
6024 ICIS_NoInit);
6025 Field->setAccess(AS_public);
6026 VaListTagDecl->addDecl(Field);
6027 }
6028 VaListTagDecl->completeDefinition();
6029 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006030 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006031
6032 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006033 TypedefDecl *VaListTagTypedefDecl =
6034 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6035
Meador Inge5d3fb222012-06-16 03:34:49 +00006036 QualType VaListTagTypedefType =
6037 Context->getTypedefType(VaListTagTypedefDecl);
6038
6039 // typedef __va_list_tag __builtin_va_list[1];
6040 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6041 QualType VaListTagArrayType
6042 = Context->getConstantArrayType(VaListTagTypedefType,
6043 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006044 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006045}
6046
6047static TypedefDecl *
6048CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6049 // typedef struct __va_list_tag {
6050 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006051 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006052 VaListTagDecl->startDefinition();
6053
6054 const size_t NumFields = 4;
6055 QualType FieldTypes[NumFields];
6056 const char *FieldNames[NumFields];
6057
6058 // unsigned gp_offset;
6059 FieldTypes[0] = Context->UnsignedIntTy;
6060 FieldNames[0] = "gp_offset";
6061
6062 // unsigned fp_offset;
6063 FieldTypes[1] = Context->UnsignedIntTy;
6064 FieldNames[1] = "fp_offset";
6065
6066 // void* overflow_arg_area;
6067 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6068 FieldNames[2] = "overflow_arg_area";
6069
6070 // void* reg_save_area;
6071 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6072 FieldNames[3] = "reg_save_area";
6073
6074 // Create fields
6075 for (unsigned i = 0; i < NumFields; ++i) {
6076 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6077 VaListTagDecl,
6078 SourceLocation(),
6079 SourceLocation(),
6080 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006081 FieldTypes[i], /*TInfo=*/nullptr,
6082 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006083 /*Mutable=*/false,
6084 ICIS_NoInit);
6085 Field->setAccess(AS_public);
6086 VaListTagDecl->addDecl(Field);
6087 }
6088 VaListTagDecl->completeDefinition();
6089 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006090 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006091
6092 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006093 TypedefDecl *VaListTagTypedefDecl =
6094 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6095
Meador Inge5d3fb222012-06-16 03:34:49 +00006096 QualType VaListTagTypedefType =
6097 Context->getTypedefType(VaListTagTypedefDecl);
6098
6099 // typedef __va_list_tag __builtin_va_list[1];
6100 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6101 QualType VaListTagArrayType
6102 = Context->getConstantArrayType(VaListTagTypedefType,
6103 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006104 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006105}
6106
6107static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6108 // typedef int __builtin_va_list[4];
6109 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6110 QualType IntArrayType
6111 = Context->getConstantArrayType(Context->IntTy,
6112 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006113 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006114}
6115
Logan Chien57086ce2012-10-10 06:56:20 +00006116static TypedefDecl *
6117CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006118 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006119 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006120 if (Context->getLangOpts().CPlusPlus) {
6121 // namespace std { struct __va_list {
6122 NamespaceDecl *NS;
6123 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6124 Context->getTranslationUnitDecl(),
6125 /*Inline*/false, SourceLocation(),
6126 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006127 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006128 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006129 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006130 }
6131
6132 VaListDecl->startDefinition();
6133
6134 // void * __ap;
6135 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6136 VaListDecl,
6137 SourceLocation(),
6138 SourceLocation(),
6139 &Context->Idents.get("__ap"),
6140 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006141 /*TInfo=*/nullptr,
6142 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006143 /*Mutable=*/false,
6144 ICIS_NoInit);
6145 Field->setAccess(AS_public);
6146 VaListDecl->addDecl(Field);
6147
6148 // };
6149 VaListDecl->completeDefinition();
6150
6151 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006152 QualType T = Context->getRecordType(VaListDecl);
6153 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006154}
6155
Ulrich Weigand47445072013-05-06 16:26:41 +00006156static TypedefDecl *
6157CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6158 // typedef struct __va_list_tag {
6159 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006160 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006161 VaListTagDecl->startDefinition();
6162
6163 const size_t NumFields = 4;
6164 QualType FieldTypes[NumFields];
6165 const char *FieldNames[NumFields];
6166
6167 // long __gpr;
6168 FieldTypes[0] = Context->LongTy;
6169 FieldNames[0] = "__gpr";
6170
6171 // long __fpr;
6172 FieldTypes[1] = Context->LongTy;
6173 FieldNames[1] = "__fpr";
6174
6175 // void *__overflow_arg_area;
6176 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6177 FieldNames[2] = "__overflow_arg_area";
6178
6179 // void *__reg_save_area;
6180 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6181 FieldNames[3] = "__reg_save_area";
6182
6183 // Create fields
6184 for (unsigned i = 0; i < NumFields; ++i) {
6185 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6186 VaListTagDecl,
6187 SourceLocation(),
6188 SourceLocation(),
6189 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006190 FieldTypes[i], /*TInfo=*/nullptr,
6191 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006192 /*Mutable=*/false,
6193 ICIS_NoInit);
6194 Field->setAccess(AS_public);
6195 VaListTagDecl->addDecl(Field);
6196 }
6197 VaListTagDecl->completeDefinition();
6198 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6199 Context->VaListTagTy = VaListTagType;
6200
6201 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006202 TypedefDecl *VaListTagTypedefDecl =
6203 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006204 QualType VaListTagTypedefType =
6205 Context->getTypedefType(VaListTagTypedefDecl);
6206
6207 // typedef __va_list_tag __builtin_va_list[1];
6208 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6209 QualType VaListTagArrayType
6210 = Context->getConstantArrayType(VaListTagTypedefType,
6211 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006212
Alp Toker56b5cc92013-12-15 10:36:26 +00006213 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006214}
6215
Meador Inge5d3fb222012-06-16 03:34:49 +00006216static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6217 TargetInfo::BuiltinVaListKind Kind) {
6218 switch (Kind) {
6219 case TargetInfo::CharPtrBuiltinVaList:
6220 return CreateCharPtrBuiltinVaListDecl(Context);
6221 case TargetInfo::VoidPtrBuiltinVaList:
6222 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006223 case TargetInfo::AArch64ABIBuiltinVaList:
6224 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006225 case TargetInfo::PowerABIBuiltinVaList:
6226 return CreatePowerABIBuiltinVaListDecl(Context);
6227 case TargetInfo::X86_64ABIBuiltinVaList:
6228 return CreateX86_64ABIBuiltinVaListDecl(Context);
6229 case TargetInfo::PNaClABIBuiltinVaList:
6230 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006231 case TargetInfo::AAPCSABIBuiltinVaList:
6232 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006233 case TargetInfo::SystemZBuiltinVaList:
6234 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006235 }
6236
6237 llvm_unreachable("Unhandled __builtin_va_list type kind");
6238}
6239
6240TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006241 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006242 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006243 assert(BuiltinVaListDecl->isImplicit());
6244 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006245
6246 return BuiltinVaListDecl;
6247}
6248
Meador Ingecfb60902012-07-01 15:57:25 +00006249QualType ASTContext::getVaListTagType() const {
6250 // Force the creation of VaListTagTy by building the __builtin_va_list
6251 // declaration.
6252 if (VaListTagTy.isNull())
6253 (void) getBuiltinVaListDecl();
6254
6255 return VaListTagTy;
6256}
6257
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006258void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006259 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006260 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006261
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006262 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006263}
6264
John McCalld28ae272009-12-02 08:04:21 +00006265/// \brief Retrieve the template name that corresponds to a non-empty
6266/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006267TemplateName
6268ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6269 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006270 unsigned size = End - Begin;
6271 assert(size > 1 && "set is not overloaded!");
6272
6273 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6274 size * sizeof(FunctionTemplateDecl*));
6275 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6276
6277 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006278 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006279 NamedDecl *D = *I;
6280 assert(isa<FunctionTemplateDecl>(D) ||
6281 (isa<UsingShadowDecl>(D) &&
6282 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6283 *Storage++ = D;
6284 }
6285
6286 return TemplateName(OT);
6287}
6288
Douglas Gregordc572a32009-03-30 22:58:21 +00006289/// \brief Retrieve the template name that represents a qualified
6290/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006291TemplateName
6292ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6293 bool TemplateKeyword,
6294 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006295 assert(NNS && "Missing nested-name-specifier in qualified template name");
6296
Douglas Gregorc42075a2010-02-04 18:10:26 +00006297 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006298 llvm::FoldingSetNodeID ID;
6299 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6300
Craig Topper36250ad2014-05-12 05:36:57 +00006301 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006302 QualifiedTemplateName *QTN =
6303 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6304 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006305 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6306 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006307 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6308 }
6309
6310 return TemplateName(QTN);
6311}
6312
6313/// \brief Retrieve the template name that represents a dependent
6314/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006315TemplateName
6316ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6317 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006318 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006319 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006320
6321 llvm::FoldingSetNodeID ID;
6322 DependentTemplateName::Profile(ID, NNS, Name);
6323
Craig Topper36250ad2014-05-12 05:36:57 +00006324 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006325 DependentTemplateName *QTN =
6326 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6327
6328 if (QTN)
6329 return TemplateName(QTN);
6330
6331 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6332 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006333 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6334 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006335 } else {
6336 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006337 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6338 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006339 DependentTemplateName *CheckQTN =
6340 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6341 assert(!CheckQTN && "Dependent type name canonicalization broken");
6342 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006343 }
6344
6345 DependentTemplateNames.InsertNode(QTN, InsertPos);
6346 return TemplateName(QTN);
6347}
6348
Douglas Gregor71395fa2009-11-04 00:56:37 +00006349/// \brief Retrieve the template name that represents a dependent
6350/// template name such as \c MetaFun::template operator+.
6351TemplateName
6352ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006353 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006354 assert((!NNS || NNS->isDependent()) &&
6355 "Nested name specifier must be dependent");
6356
6357 llvm::FoldingSetNodeID ID;
6358 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006359
6360 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006361 DependentTemplateName *QTN
6362 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006363
6364 if (QTN)
6365 return TemplateName(QTN);
6366
6367 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6368 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006369 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6370 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006371 } else {
6372 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006373 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6374 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006375
6376 DependentTemplateName *CheckQTN
6377 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6378 assert(!CheckQTN && "Dependent template name canonicalization broken");
6379 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006380 }
6381
6382 DependentTemplateNames.InsertNode(QTN, InsertPos);
6383 return TemplateName(QTN);
6384}
6385
Douglas Gregor5590be02011-01-15 06:45:20 +00006386TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006387ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6388 TemplateName replacement) const {
6389 llvm::FoldingSetNodeID ID;
6390 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006391
6392 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006393 SubstTemplateTemplateParmStorage *subst
6394 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6395
6396 if (!subst) {
6397 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6398 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6399 }
6400
6401 return TemplateName(subst);
6402}
6403
6404TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006405ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6406 const TemplateArgument &ArgPack) const {
6407 ASTContext &Self = const_cast<ASTContext &>(*this);
6408 llvm::FoldingSetNodeID ID;
6409 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006410
6411 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006412 SubstTemplateTemplateParmPackStorage *Subst
6413 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6414
6415 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006416 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006417 ArgPack.pack_size(),
6418 ArgPack.pack_begin());
6419 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6420 }
6421
6422 return TemplateName(Subst);
6423}
6424
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006425/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006426/// TargetInfo, produce the corresponding type. The unsigned @p Type
6427/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006428CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006429 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006430 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006431 case TargetInfo::SignedChar: return SignedCharTy;
6432 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006433 case TargetInfo::SignedShort: return ShortTy;
6434 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6435 case TargetInfo::SignedInt: return IntTy;
6436 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6437 case TargetInfo::SignedLong: return LongTy;
6438 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6439 case TargetInfo::SignedLongLong: return LongLongTy;
6440 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6441 }
6442
David Blaikie83d382b2011-09-23 05:06:16 +00006443 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006444}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006445
6446//===----------------------------------------------------------------------===//
6447// Type Predicates.
6448//===----------------------------------------------------------------------===//
6449
Fariborz Jahanian96207692009-02-18 21:49:28 +00006450/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6451/// garbage collection attribute.
6452///
John McCall553d45a2011-01-12 00:34:59 +00006453Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006454 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006455 return Qualifiers::GCNone;
6456
David Blaikiebbafb8a2012-03-11 07:00:24 +00006457 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006458 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6459
6460 // Default behaviour under objective-C's gc is for ObjC pointers
6461 // (or pointers to them) be treated as though they were declared
6462 // as __strong.
6463 if (GCAttrs == Qualifiers::GCNone) {
6464 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6465 return Qualifiers::Strong;
6466 else if (Ty->isPointerType())
6467 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6468 } else {
6469 // It's not valid to set GC attributes on anything that isn't a
6470 // pointer.
6471#ifndef NDEBUG
6472 QualType CT = Ty->getCanonicalTypeInternal();
6473 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6474 CT = AT->getElementType();
6475 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6476#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006477 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006478 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006479}
6480
Chris Lattner49af6a42008-04-07 06:51:04 +00006481//===----------------------------------------------------------------------===//
6482// Type Compatibility Testing
6483//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006484
Mike Stump11289f42009-09-09 15:08:12 +00006485/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006486/// compatible.
6487static bool areCompatVectorTypes(const VectorType *LHS,
6488 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006489 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006490 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006491 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006492}
6493
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006494bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6495 QualType SecondVec) {
6496 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6497 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6498
6499 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6500 return true;
6501
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006502 // Treat Neon vector types and most AltiVec vector types as if they are the
6503 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006504 const VectorType *First = FirstVec->getAs<VectorType>();
6505 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006506 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006507 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006508 First->getVectorKind() != VectorType::AltiVecPixel &&
6509 First->getVectorKind() != VectorType::AltiVecBool &&
6510 Second->getVectorKind() != VectorType::AltiVecPixel &&
6511 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006512 return true;
6513
6514 return false;
6515}
6516
Steve Naroff8e6aee52009-07-23 01:01:38 +00006517//===----------------------------------------------------------------------===//
6518// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6519//===----------------------------------------------------------------------===//
6520
6521/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6522/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006523bool
6524ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6525 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006526 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006527 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006528 for (auto *PI : rProto->protocols())
6529 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006530 return true;
6531 return false;
6532}
6533
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006534/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6535/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006536bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6537 QualType rhs) {
6538 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6539 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6540 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6541
Aaron Ballman83731462014-03-17 16:14:00 +00006542 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006543 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006544 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006545 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6546 match = true;
6547 break;
6548 }
6549 }
6550 if (!match)
6551 return false;
6552 }
6553 return true;
6554}
6555
Steve Naroff8e6aee52009-07-23 01:01:38 +00006556/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6557/// ObjCQualifiedIDType.
6558bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6559 bool compare) {
6560 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006561 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006562 lhs->isObjCIdType() || lhs->isObjCClassType())
6563 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006564 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006565 rhs->isObjCIdType() || rhs->isObjCClassType())
6566 return true;
6567
6568 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006569 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006570
Steve Naroff8e6aee52009-07-23 01:01:38 +00006571 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006572
Steve Naroff8e6aee52009-07-23 01:01:38 +00006573 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006574 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006575 // make sure we check the class hierarchy.
6576 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006577 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006578 // when comparing an id<P> on lhs with a static type on rhs,
6579 // see if static class implements all of id's protocols, directly or
6580 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006581 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006582 return false;
6583 }
6584 }
6585 // If there are no qualifiers and no interface, we have an 'id'.
6586 return true;
6587 }
Mike Stump11289f42009-09-09 15:08:12 +00006588 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006589 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006590 bool match = false;
6591
6592 // when comparing an id<P> on lhs with a static type on rhs,
6593 // see if static class implements all of id's protocols, directly or
6594 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006595 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006596 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6597 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6598 match = true;
6599 break;
6600 }
6601 }
Mike Stump11289f42009-09-09 15:08:12 +00006602 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006603 // make sure we check the class hierarchy.
6604 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006605 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006606 // when comparing an id<P> on lhs with a static type on rhs,
6607 // see if static class implements all of id's protocols, directly or
6608 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006609 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006610 match = true;
6611 break;
6612 }
6613 }
6614 }
6615 if (!match)
6616 return false;
6617 }
Mike Stump11289f42009-09-09 15:08:12 +00006618
Steve Naroff8e6aee52009-07-23 01:01:38 +00006619 return true;
6620 }
Mike Stump11289f42009-09-09 15:08:12 +00006621
Steve Naroff8e6aee52009-07-23 01:01:38 +00006622 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6623 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6624
Mike Stump11289f42009-09-09 15:08:12 +00006625 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006626 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006627 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006628 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006629 bool match = false;
6630
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006631 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006632 // see if static class implements all of id's protocols, directly or
6633 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006634 // First, lhs protocols in the qualifier list must be found, direct
6635 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006636 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006637 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6638 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6639 match = true;
6640 break;
6641 }
6642 }
6643 if (!match)
6644 return false;
6645 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006646
6647 // Static class's protocols, or its super class or category protocols
6648 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6649 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6650 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6651 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6652 // This is rather dubious but matches gcc's behavior. If lhs has
6653 // no type qualifier and its class has no static protocol(s)
6654 // assume that it is mismatch.
6655 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6656 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006657 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006658 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006659 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006660 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6661 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6662 match = true;
6663 break;
6664 }
6665 }
6666 if (!match)
6667 return false;
6668 }
6669 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006670 return true;
6671 }
6672 return false;
6673}
6674
Eli Friedman47f77112008-08-22 00:56:42 +00006675/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006676/// compatible for assignment from RHS to LHS. This handles validation of any
6677/// protocol qualifiers on the LHS or RHS.
6678///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006679bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6680 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006681 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6682 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6683
Steve Naroff1329fa02009-07-15 18:40:39 +00006684 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006685 if (LHS->isObjCUnqualifiedIdOrClass() ||
6686 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006687 return true;
6688
John McCall8b07ec22010-05-15 11:32:37 +00006689 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006690 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6691 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006692 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006693
6694 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6695 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6696 QualType(RHSOPT,0));
6697
John McCall8b07ec22010-05-15 11:32:37 +00006698 // If we have 2 user-defined types, fall into that path.
6699 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006700 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006701
Steve Naroff8e6aee52009-07-23 01:01:38 +00006702 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006703}
6704
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006705/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006706/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006707/// arguments in block literals. When passed as arguments, passing 'A*' where
6708/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6709/// not OK. For the return type, the opposite is not OK.
6710bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6711 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006712 const ObjCObjectPointerType *RHSOPT,
6713 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006714 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006715 return true;
6716
6717 if (LHSOPT->isObjCBuiltinType()) {
6718 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6719 }
6720
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006721 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006722 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6723 QualType(RHSOPT,0),
6724 false);
6725
6726 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6727 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6728 if (LHS && RHS) { // We have 2 user-defined types.
6729 if (LHS != RHS) {
6730 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006731 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006732 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006733 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006734 }
6735 else
6736 return true;
6737 }
6738 return false;
6739}
6740
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006741/// getIntersectionOfProtocols - This routine finds the intersection of set
6742/// of protocols inherited from two distinct objective-c pointer objects.
6743/// It is used to build composite qualifier list of the composite type of
6744/// the conditional expression involving two objective-c pointer objects.
6745static
6746void getIntersectionOfProtocols(ASTContext &Context,
6747 const ObjCObjectPointerType *LHSOPT,
6748 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006749 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006750
John McCall8b07ec22010-05-15 11:32:37 +00006751 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6752 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6753 assert(LHS->getInterface() && "LHS must have an interface base");
6754 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006755
6756 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6757 unsigned LHSNumProtocols = LHS->getNumProtocols();
6758 if (LHSNumProtocols > 0)
6759 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6760 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006761 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006762 Context.CollectInheritedProtocols(LHS->getInterface(),
6763 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006764 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6765 LHSInheritedProtocols.end());
6766 }
6767
6768 unsigned RHSNumProtocols = RHS->getNumProtocols();
6769 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006770 ObjCProtocolDecl **RHSProtocols =
6771 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006772 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6773 if (InheritedProtocolSet.count(RHSProtocols[i]))
6774 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006775 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006776 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006777 Context.CollectInheritedProtocols(RHS->getInterface(),
6778 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006779 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6780 if (InheritedProtocolSet.count(ProtDecl))
6781 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006782 }
6783}
6784
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006785/// areCommonBaseCompatible - Returns common base class of the two classes if
6786/// one found. Note that this is O'2 algorithm. But it will be called as the
6787/// last type comparison in a ?-exp of ObjC pointer types before a
6788/// warning is issued. So, its invokation is extremely rare.
6789QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006790 const ObjCObjectPointerType *Lptr,
6791 const ObjCObjectPointerType *Rptr) {
6792 const ObjCObjectType *LHS = Lptr->getObjectType();
6793 const ObjCObjectType *RHS = Rptr->getObjectType();
6794 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6795 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006796 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006797 return QualType();
6798
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006799 do {
John McCall8b07ec22010-05-15 11:32:37 +00006800 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006801 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006802 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006803 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6804
6805 QualType Result = QualType(LHS, 0);
6806 if (!Protocols.empty())
6807 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6808 Result = getObjCObjectPointerType(Result);
6809 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006810 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006811 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006812
6813 return QualType();
6814}
6815
John McCall8b07ec22010-05-15 11:32:37 +00006816bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6817 const ObjCObjectType *RHS) {
6818 assert(LHS->getInterface() && "LHS is not an interface type");
6819 assert(RHS->getInterface() && "RHS is not an interface type");
6820
Chris Lattner49af6a42008-04-07 06:51:04 +00006821 // Verify that the base decls are compatible: the RHS must be a subclass of
6822 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006823 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006824 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006825
Chris Lattner49af6a42008-04-07 06:51:04 +00006826 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6827 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006828 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006829 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006830
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006831 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6832 // More detailed analysis is required.
6833 // OK, if LHS is same or a superclass of RHS *and*
6834 // this LHS, or as RHS's super class is assignment compatible with LHS.
6835 bool IsSuperClass =
6836 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6837 if (IsSuperClass) {
6838 // OK if conversion of LHS to SuperClass results in narrowing of types
6839 // ; i.e., SuperClass may implement at least one of the protocols
6840 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6841 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6842 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6843 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6844 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6845 // qualifiers.
6846 for (auto *RHSPI : RHS->quals())
6847 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6848 // If there is no protocols associated with RHS, it is not a match.
6849 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006850 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006851
6852 for (const auto *LHSProto : LHS->quals()) {
6853 bool SuperImplementsProtocol = false;
6854 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6855 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6856 SuperImplementsProtocol = true;
6857 break;
6858 }
6859 if (!SuperImplementsProtocol)
6860 return false;
6861 }
6862 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006863 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006864 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006865}
6866
Steve Naroffb7605152009-02-12 17:52:19 +00006867bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6868 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006869 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6870 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006871
Steve Naroff7cae42b2009-07-10 23:34:53 +00006872 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006873 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006874
6875 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6876 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006877}
6878
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006879bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6880 return canAssignObjCInterfaces(
6881 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6882 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6883}
6884
Mike Stump11289f42009-09-09 15:08:12 +00006885/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006886/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006887/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006888/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006889bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6890 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006891 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006892 return hasSameType(LHS, RHS);
6893
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006894 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006895}
6896
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006897bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006898 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006899}
6900
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006901bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6902 return !mergeTypes(LHS, RHS, true).isNull();
6903}
6904
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006905/// mergeTransparentUnionType - if T is a transparent union type and a member
6906/// of T is compatible with SubType, return the merged type, else return
6907/// QualType()
6908QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6909 bool OfBlockPointer,
6910 bool Unqualified) {
6911 if (const RecordType *UT = T->getAsUnionType()) {
6912 RecordDecl *UD = UT->getDecl();
6913 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006914 for (const auto *I : UD->fields()) {
6915 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006916 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6917 if (!MT.isNull())
6918 return MT;
6919 }
6920 }
6921 }
6922
6923 return QualType();
6924}
6925
Alp Toker9cacbab2014-01-20 20:26:09 +00006926/// mergeFunctionParameterTypes - merge two types which appear as function
6927/// parameter types
6928QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6929 bool OfBlockPointer,
6930 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006931 // GNU extension: two types are compatible if they appear as a function
6932 // argument, one of the types is a transparent union type and the other
6933 // type is compatible with a union member
6934 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6935 Unqualified);
6936 if (!lmerge.isNull())
6937 return lmerge;
6938
6939 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6940 Unqualified);
6941 if (!rmerge.isNull())
6942 return rmerge;
6943
6944 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6945}
6946
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006947QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006948 bool OfBlockPointer,
6949 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006950 const FunctionType *lbase = lhs->getAs<FunctionType>();
6951 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006952 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6953 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006954 bool allLTypes = true;
6955 bool allRTypes = true;
6956
6957 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006958 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006959 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006960 QualType RHS = rbase->getReturnType();
6961 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006962 bool UnqualifiedResult = Unqualified;
6963 if (!UnqualifiedResult)
6964 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006965 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006966 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006967 else
Alp Toker314cc812014-01-25 16:55:45 +00006968 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006969 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006970 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006971
6972 if (Unqualified)
6973 retType = retType.getUnqualifiedType();
6974
Alp Toker314cc812014-01-25 16:55:45 +00006975 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6976 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006977 if (Unqualified) {
6978 LRetType = LRetType.getUnqualifiedType();
6979 RRetType = RRetType.getUnqualifiedType();
6980 }
6981
6982 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006983 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006984 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006985 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006986
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006987 // FIXME: double check this
6988 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6989 // rbase->getRegParmAttr() != 0 &&
6990 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006991 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6992 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006993
Douglas Gregor8c940862010-01-18 17:14:39 +00006994 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006995 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006996 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006997
John McCall8c6b56f2010-12-15 01:06:38 +00006998 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006999 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7000 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007001 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7002 return QualType();
7003
John McCall31168b02011-06-15 23:02:42 +00007004 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7005 return QualType();
7006
John McCall8c6b56f2010-12-15 01:06:38 +00007007 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7008 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007009
Rafael Espindola8778c282012-11-29 16:09:03 +00007010 if (lbaseInfo.getNoReturn() != NoReturn)
7011 allLTypes = false;
7012 if (rbaseInfo.getNoReturn() != NoReturn)
7013 allRTypes = false;
7014
John McCall31168b02011-06-15 23:02:42 +00007015 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007016
Eli Friedman47f77112008-08-22 00:56:42 +00007017 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007018 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7019 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007020 // Compatible functions must have the same number of parameters
7021 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007022 return QualType();
7023
7024 // Variadic and non-variadic functions aren't compatible
7025 if (lproto->isVariadic() != rproto->isVariadic())
7026 return QualType();
7027
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007028 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7029 return QualType();
7030
Fariborz Jahanian97676972011-09-28 21:52:05 +00007031 if (LangOpts.ObjCAutoRefCount &&
7032 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7033 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007034
7035 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007036 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007037 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7038 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7039 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7040 QualType paramType = mergeFunctionParameterTypes(
7041 lParamType, rParamType, OfBlockPointer, Unqualified);
7042 if (paramType.isNull())
7043 return QualType();
7044
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007045 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007046 paramType = paramType.getUnqualifiedType();
7047
7048 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007049 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007050 lParamType = lParamType.getUnqualifiedType();
7051 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007052 }
Alp Toker601b22c2014-01-21 23:35:24 +00007053
7054 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007055 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007056 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007057 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007058 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007059
Eli Friedman47f77112008-08-22 00:56:42 +00007060 if (allLTypes) return lhs;
7061 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007062
7063 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7064 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007065 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007066 }
7067
7068 if (lproto) allRTypes = false;
7069 if (rproto) allLTypes = false;
7070
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007071 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007072 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007073 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007074 if (proto->isVariadic()) return QualType();
7075 // Check that the types are compatible with the types that
7076 // would result from default argument promotions (C99 6.7.5.3p15).
7077 // The only types actually affected are promotable integer
7078 // types and floats, which would be passed as a different
7079 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007080 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7081 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007082
Eli Friedman448ce402012-08-30 00:44:15 +00007083 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007084 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007085 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7086 paramTy = Enum->getDecl()->getIntegerType();
7087 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007088 return QualType();
7089 }
Alp Toker601b22c2014-01-21 23:35:24 +00007090
7091 if (paramTy->isPromotableIntegerType() ||
7092 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007093 return QualType();
7094 }
7095
7096 if (allLTypes) return lhs;
7097 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007098
7099 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7100 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007101 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007102 }
7103
7104 if (allLTypes) return lhs;
7105 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007106 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007107}
7108
John McCall433c2e62013-03-21 00:10:07 +00007109/// Given that we have an enum type and a non-enum type, try to merge them.
7110static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7111 QualType other, bool isBlockReturnType) {
7112 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7113 // a signed integer type, or an unsigned integer type.
7114 // Compatibility is based on the underlying type, not the promotion
7115 // type.
7116 QualType underlyingType = ET->getDecl()->getIntegerType();
7117 if (underlyingType.isNull()) return QualType();
7118 if (Context.hasSameType(underlyingType, other))
7119 return other;
7120
7121 // In block return types, we're more permissive and accept any
7122 // integral type of the same size.
7123 if (isBlockReturnType && other->isIntegerType() &&
7124 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7125 return other;
7126
7127 return QualType();
7128}
7129
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007130QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007131 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007132 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007133 // C++ [expr]: If an expression initially has the type "reference to T", the
7134 // type is adjusted to "T" prior to any further analysis, the expression
7135 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007136 // expression is an lvalue unless the reference is an rvalue reference and
7137 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007138 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7139 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007140
7141 if (Unqualified) {
7142 LHS = LHS.getUnqualifiedType();
7143 RHS = RHS.getUnqualifiedType();
7144 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007145
Eli Friedman47f77112008-08-22 00:56:42 +00007146 QualType LHSCan = getCanonicalType(LHS),
7147 RHSCan = getCanonicalType(RHS);
7148
7149 // If two types are identical, they are compatible.
7150 if (LHSCan == RHSCan)
7151 return LHS;
7152
John McCall8ccfcb52009-09-24 19:53:00 +00007153 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007154 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7155 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007156 if (LQuals != RQuals) {
7157 // If any of these qualifiers are different, we have a type
7158 // mismatch.
7159 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007160 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7161 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007162 return QualType();
7163
7164 // Exactly one GC qualifier difference is allowed: __strong is
7165 // okay if the other type has no GC qualifier but is an Objective
7166 // C object pointer (i.e. implicitly strong by default). We fix
7167 // this by pretending that the unqualified type was actually
7168 // qualified __strong.
7169 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7170 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7171 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7172
7173 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7174 return QualType();
7175
7176 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7177 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7178 }
7179 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7180 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7181 }
Eli Friedman47f77112008-08-22 00:56:42 +00007182 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007183 }
7184
7185 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007186
Eli Friedmandcca6332009-06-01 01:22:52 +00007187 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7188 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007189
Chris Lattnerfd652912008-01-14 05:45:46 +00007190 // We want to consider the two function types to be the same for these
7191 // comparisons, just force one to the other.
7192 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7193 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007194
7195 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007196 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7197 LHSClass = Type::ConstantArray;
7198 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7199 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007200
John McCall8b07ec22010-05-15 11:32:37 +00007201 // ObjCInterfaces are just specialized ObjCObjects.
7202 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7203 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7204
Nate Begemance4d7fc2008-04-18 23:10:10 +00007205 // Canonicalize ExtVector -> Vector.
7206 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7207 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007208
Chris Lattner95554662008-04-07 05:43:21 +00007209 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007210 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007211 // Note that we only have special rules for turning block enum
7212 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007213 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007214 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007215 }
John McCall9dd450b2009-09-21 23:43:11 +00007216 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007217 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007218 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007219 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007220 if (OfBlockPointer && !BlockReturnType) {
7221 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7222 return LHS;
7223 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7224 return RHS;
7225 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007226
Eli Friedman47f77112008-08-22 00:56:42 +00007227 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007228 }
Eli Friedman47f77112008-08-22 00:56:42 +00007229
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007230 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007231 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007232#define TYPE(Class, Base)
7233#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007234#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007235#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7236#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7237#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007238 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007239
Richard Smith27d807c2013-04-30 13:56:41 +00007240 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007241 case Type::LValueReference:
7242 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007243 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007244 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007245
John McCall8b07ec22010-05-15 11:32:37 +00007246 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007247 case Type::IncompleteArray:
7248 case Type::VariableArray:
7249 case Type::FunctionProto:
7250 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007251 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007252
Chris Lattnerfd652912008-01-14 05:45:46 +00007253 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007254 {
7255 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007256 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7257 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007258 if (Unqualified) {
7259 LHSPointee = LHSPointee.getUnqualifiedType();
7260 RHSPointee = RHSPointee.getUnqualifiedType();
7261 }
7262 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7263 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007264 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007265 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007266 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007267 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007268 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007269 return getPointerType(ResultType);
7270 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007271 case Type::BlockPointer:
7272 {
7273 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007274 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7275 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007276 if (Unqualified) {
7277 LHSPointee = LHSPointee.getUnqualifiedType();
7278 RHSPointee = RHSPointee.getUnqualifiedType();
7279 }
7280 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7281 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007282 if (ResultType.isNull()) return QualType();
7283 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7284 return LHS;
7285 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7286 return RHS;
7287 return getBlockPointerType(ResultType);
7288 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007289 case Type::Atomic:
7290 {
7291 // Merge two pointer types, while trying to preserve typedef info
7292 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7293 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7294 if (Unqualified) {
7295 LHSValue = LHSValue.getUnqualifiedType();
7296 RHSValue = RHSValue.getUnqualifiedType();
7297 }
7298 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7299 Unqualified);
7300 if (ResultType.isNull()) return QualType();
7301 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7302 return LHS;
7303 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7304 return RHS;
7305 return getAtomicType(ResultType);
7306 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007307 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007308 {
7309 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7310 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7311 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7312 return QualType();
7313
7314 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7315 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007316 if (Unqualified) {
7317 LHSElem = LHSElem.getUnqualifiedType();
7318 RHSElem = RHSElem.getUnqualifiedType();
7319 }
7320
7321 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007322 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007323 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7324 return LHS;
7325 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7326 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007327 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7328 ArrayType::ArraySizeModifier(), 0);
7329 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7330 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007331 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7332 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007333 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7334 return LHS;
7335 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7336 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007337 if (LVAT) {
7338 // FIXME: This isn't correct! But tricky to implement because
7339 // the array's size has to be the size of LHS, but the type
7340 // has to be different.
7341 return LHS;
7342 }
7343 if (RVAT) {
7344 // FIXME: This isn't correct! But tricky to implement because
7345 // the array's size has to be the size of RHS, but the type
7346 // has to be different.
7347 return RHS;
7348 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007349 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7350 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007351 return getIncompleteArrayType(ResultType,
7352 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007353 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007354 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007355 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007356 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007357 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007358 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007359 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007360 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007361 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007362 case Type::Complex:
7363 // Distinct complex types are incompatible.
7364 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007365 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007366 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007367 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7368 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007369 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007370 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007371 case Type::ObjCObject: {
7372 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007373 // FIXME: This should be type compatibility, e.g. whether
7374 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007375 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7376 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7377 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007378 return LHS;
7379
Eli Friedman47f77112008-08-22 00:56:42 +00007380 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007381 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007382 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007383 if (OfBlockPointer) {
7384 if (canAssignObjCInterfacesInBlockPointer(
7385 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007386 RHS->getAs<ObjCObjectPointerType>(),
7387 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007388 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007389 return QualType();
7390 }
John McCall9dd450b2009-09-21 23:43:11 +00007391 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7392 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007393 return LHS;
7394
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007395 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007396 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007397 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007398
David Blaikie8a40f702012-01-17 06:56:22 +00007399 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007400}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007401
Fariborz Jahanian97676972011-09-28 21:52:05 +00007402bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7403 const FunctionProtoType *FromFunctionType,
7404 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007405 if (FromFunctionType->hasAnyConsumedParams() !=
7406 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007407 return false;
7408 FunctionProtoType::ExtProtoInfo FromEPI =
7409 FromFunctionType->getExtProtoInfo();
7410 FunctionProtoType::ExtProtoInfo ToEPI =
7411 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007412 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007413 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7414 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007415 return false;
7416 }
7417 return true;
7418}
7419
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007420/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7421/// 'RHS' attributes and returns the merged version; including for function
7422/// return types.
7423QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7424 QualType LHSCan = getCanonicalType(LHS),
7425 RHSCan = getCanonicalType(RHS);
7426 // If two types are identical, they are compatible.
7427 if (LHSCan == RHSCan)
7428 return LHS;
7429 if (RHSCan->isFunctionType()) {
7430 if (!LHSCan->isFunctionType())
7431 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007432 QualType OldReturnType =
7433 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007434 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007435 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007436 QualType ResReturnType =
7437 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7438 if (ResReturnType.isNull())
7439 return QualType();
7440 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7441 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7442 // In either case, use OldReturnType to build the new function type.
7443 const FunctionType *F = LHS->getAs<FunctionType>();
7444 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007445 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7446 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007447 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007448 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007449 return ResultType;
7450 }
7451 }
7452 return QualType();
7453 }
7454
7455 // If the qualifiers are different, the types can still be merged.
7456 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7457 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7458 if (LQuals != RQuals) {
7459 // If any of these qualifiers are different, we have a type mismatch.
7460 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7461 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7462 return QualType();
7463
7464 // Exactly one GC qualifier difference is allowed: __strong is
7465 // okay if the other type has no GC qualifier but is an Objective
7466 // C object pointer (i.e. implicitly strong by default). We fix
7467 // this by pretending that the unqualified type was actually
7468 // qualified __strong.
7469 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7470 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7471 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7472
7473 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7474 return QualType();
7475
7476 if (GC_L == Qualifiers::Strong)
7477 return LHS;
7478 if (GC_R == Qualifiers::Strong)
7479 return RHS;
7480 return QualType();
7481 }
7482
7483 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7484 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7485 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7486 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7487 if (ResQT == LHSBaseQT)
7488 return LHS;
7489 if (ResQT == RHSBaseQT)
7490 return RHS;
7491 }
7492 return QualType();
7493}
7494
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007495//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007496// Integer Predicates
7497//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007498
Jay Foad39c79802011-01-12 09:06:06 +00007499unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007500 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007501 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007502 if (T->isBooleanType())
7503 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007504 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007505 return (unsigned)getTypeSize(T);
7506}
7507
Abramo Bagnara13640492012-09-09 10:21:24 +00007508QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007509 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007510
7511 // Turn <4 x signed int> -> <4 x unsigned int>
7512 if (const VectorType *VTy = T->getAs<VectorType>())
7513 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007514 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007515
7516 // For enums, we return the unsigned version of the base type.
7517 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007518 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007519
7520 const BuiltinType *BTy = T->getAs<BuiltinType>();
7521 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007522 switch (BTy->getKind()) {
7523 case BuiltinType::Char_S:
7524 case BuiltinType::SChar:
7525 return UnsignedCharTy;
7526 case BuiltinType::Short:
7527 return UnsignedShortTy;
7528 case BuiltinType::Int:
7529 return UnsignedIntTy;
7530 case BuiltinType::Long:
7531 return UnsignedLongTy;
7532 case BuiltinType::LongLong:
7533 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007534 case BuiltinType::Int128:
7535 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007536 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007537 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007538 }
7539}
7540
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007541ASTMutationListener::~ASTMutationListener() { }
7542
Richard Smith1fa5d642013-05-11 05:45:24 +00007543void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7544 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007545
7546//===----------------------------------------------------------------------===//
7547// Builtin Type Computation
7548//===----------------------------------------------------------------------===//
7549
7550/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007551/// pointer over the consumed characters. This returns the resultant type. If
7552/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7553/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7554/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007555///
7556/// RequiresICE is filled in on return to indicate whether the value is required
7557/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007558static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007559 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007560 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007561 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007562 // Modifiers.
7563 int HowLong = 0;
7564 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007565 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007566
Chris Lattnerdc226c22010-10-01 22:42:38 +00007567 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007568 bool Done = false;
7569 while (!Done) {
7570 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007571 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007572 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007573 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007574 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007575 case 'S':
7576 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7577 assert(!Signed && "Can't use 'S' modifier multiple times!");
7578 Signed = true;
7579 break;
7580 case 'U':
7581 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007582 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007583 Unsigned = true;
7584 break;
7585 case 'L':
7586 assert(HowLong <= 2 && "Can't have LLLL modifier");
7587 ++HowLong;
7588 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007589 case 'W':
7590 // This modifier represents int64 type.
7591 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7592 switch (Context.getTargetInfo().getInt64Type()) {
7593 default:
7594 llvm_unreachable("Unexpected integer type");
7595 case TargetInfo::SignedLong:
7596 HowLong = 1;
7597 break;
7598 case TargetInfo::SignedLongLong:
7599 HowLong = 2;
7600 break;
7601 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007602 }
7603 }
7604
7605 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007606
Chris Lattnerecd79c62009-06-14 00:45:47 +00007607 // Read the base type.
7608 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007609 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007610 case 'v':
7611 assert(HowLong == 0 && !Signed && !Unsigned &&
7612 "Bad modifiers used with 'v'!");
7613 Type = Context.VoidTy;
7614 break;
Jack Carter24bef982013-08-15 15:16:57 +00007615 case 'h':
7616 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007617 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007618 Type = Context.HalfTy;
7619 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007620 case 'f':
7621 assert(HowLong == 0 && !Signed && !Unsigned &&
7622 "Bad modifiers used with 'f'!");
7623 Type = Context.FloatTy;
7624 break;
7625 case 'd':
7626 assert(HowLong < 2 && !Signed && !Unsigned &&
7627 "Bad modifiers used with 'd'!");
7628 if (HowLong)
7629 Type = Context.LongDoubleTy;
7630 else
7631 Type = Context.DoubleTy;
7632 break;
7633 case 's':
7634 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7635 if (Unsigned)
7636 Type = Context.UnsignedShortTy;
7637 else
7638 Type = Context.ShortTy;
7639 break;
7640 case 'i':
7641 if (HowLong == 3)
7642 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7643 else if (HowLong == 2)
7644 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7645 else if (HowLong == 1)
7646 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7647 else
7648 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7649 break;
7650 case 'c':
7651 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7652 if (Signed)
7653 Type = Context.SignedCharTy;
7654 else if (Unsigned)
7655 Type = Context.UnsignedCharTy;
7656 else
7657 Type = Context.CharTy;
7658 break;
7659 case 'b': // boolean
7660 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7661 Type = Context.BoolTy;
7662 break;
7663 case 'z': // size_t.
7664 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7665 Type = Context.getSizeType();
7666 break;
7667 case 'F':
7668 Type = Context.getCFConstantStringType();
7669 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007670 case 'G':
7671 Type = Context.getObjCIdType();
7672 break;
7673 case 'H':
7674 Type = Context.getObjCSelType();
7675 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007676 case 'M':
7677 Type = Context.getObjCSuperType();
7678 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007679 case 'a':
7680 Type = Context.getBuiltinVaListType();
7681 assert(!Type.isNull() && "builtin va list type not initialized!");
7682 break;
7683 case 'A':
7684 // This is a "reference" to a va_list; however, what exactly
7685 // this means depends on how va_list is defined. There are two
7686 // different kinds of va_list: ones passed by value, and ones
7687 // passed by reference. An example of a by-value va_list is
7688 // x86, where va_list is a char*. An example of by-ref va_list
7689 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7690 // we want this argument to be a char*&; for x86-64, we want
7691 // it to be a __va_list_tag*.
7692 Type = Context.getBuiltinVaListType();
7693 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007694 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007695 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007696 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007697 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007698 break;
7699 case 'V': {
7700 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007701 unsigned NumElements = strtoul(Str, &End, 10);
7702 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007703 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007704
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007705 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7706 RequiresICE, false);
7707 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007708
7709 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007710 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007711 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007712 break;
7713 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007714 case 'E': {
7715 char *End;
7716
7717 unsigned NumElements = strtoul(Str, &End, 10);
7718 assert(End != Str && "Missing vector size");
7719
7720 Str = End;
7721
7722 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7723 false);
7724 Type = Context.getExtVectorType(ElementType, NumElements);
7725 break;
7726 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007727 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007728 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7729 false);
7730 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007731 Type = Context.getComplexType(ElementType);
7732 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007733 }
7734 case 'Y' : {
7735 Type = Context.getPointerDiffType();
7736 break;
7737 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007738 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007739 Type = Context.getFILEType();
7740 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007741 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007742 return QualType();
7743 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007744 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007745 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007746 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007747 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007748 else
7749 Type = Context.getjmp_bufType();
7750
Mike Stump2adb4da2009-07-28 23:47:15 +00007751 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007752 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007753 return QualType();
7754 }
7755 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007756 case 'K':
7757 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7758 Type = Context.getucontext_tType();
7759
7760 if (Type.isNull()) {
7761 Error = ASTContext::GE_Missing_ucontext;
7762 return QualType();
7763 }
7764 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007765 case 'p':
7766 Type = Context.getProcessIDType();
7767 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007768 }
Mike Stump11289f42009-09-09 15:08:12 +00007769
Chris Lattnerdc226c22010-10-01 22:42:38 +00007770 // If there are modifiers and if we're allowed to parse them, go for it.
7771 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007772 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007773 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007774 default: Done = true; --Str; break;
7775 case '*':
7776 case '&': {
7777 // Both pointers and references can have their pointee types
7778 // qualified with an address space.
7779 char *End;
7780 unsigned AddrSpace = strtoul(Str, &End, 10);
7781 if (End != Str && AddrSpace != 0) {
7782 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7783 Str = End;
7784 }
7785 if (c == '*')
7786 Type = Context.getPointerType(Type);
7787 else
7788 Type = Context.getLValueReferenceType(Type);
7789 break;
7790 }
7791 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7792 case 'C':
7793 Type = Type.withConst();
7794 break;
7795 case 'D':
7796 Type = Context.getVolatileType(Type);
7797 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007798 case 'R':
7799 Type = Type.withRestrict();
7800 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007801 }
7802 }
Chris Lattner84733392010-10-01 07:13:18 +00007803
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007804 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007805 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007806
Chris Lattnerecd79c62009-06-14 00:45:47 +00007807 return Type;
7808}
7809
7810/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007811QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007812 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007813 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007814 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007815
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007816 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007817
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007818 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007819 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007820 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7821 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007822 if (Error != GE_None)
7823 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007824
7825 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7826
Chris Lattnerecd79c62009-06-14 00:45:47 +00007827 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007828 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007829 if (Error != GE_None)
7830 return QualType();
7831
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007832 // If this argument is required to be an IntegerConstantExpression and the
7833 // caller cares, fill in the bitmask we return.
7834 if (RequiresICE && IntegerConstantArgs)
7835 *IntegerConstantArgs |= 1 << ArgTypes.size();
7836
Chris Lattnerecd79c62009-06-14 00:45:47 +00007837 // Do array -> pointer decay. The builtin should use the decayed type.
7838 if (Ty->isArrayType())
7839 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007840
Chris Lattnerecd79c62009-06-14 00:45:47 +00007841 ArgTypes.push_back(Ty);
7842 }
7843
David Majnemerba3e5ec2015-03-13 18:26:17 +00007844 if (Id == Builtin::BI__GetExceptionInfo)
7845 return QualType();
7846
Chris Lattnerecd79c62009-06-14 00:45:47 +00007847 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7848 "'.' should only occur at end of builtin type list!");
7849
Reid Kleckner78af0702013-08-27 23:08:25 +00007850 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007851 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7852
7853 bool Variadic = (TypeStr[0] == '.');
7854
7855 // We really shouldn't be making a no-proto type here, especially in C++.
7856 if (ArgTypes.empty() && Variadic)
7857 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007858
John McCalldb40c7f2010-12-14 08:05:40 +00007859 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007860 EPI.ExtInfo = EI;
7861 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007862
Jordan Rose5c382722013-03-08 21:51:21 +00007863 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007864}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007865
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007866static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7867 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007868 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007869 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007870
Rafael Espindola3ae00052013-05-13 00:12:11 +00007871 GVALinkage External = GVA_StrongExternal;
7872 switch (FD->getTemplateSpecializationKind()) {
7873 case TSK_Undeclared:
7874 case TSK_ExplicitSpecialization:
7875 External = GVA_StrongExternal;
7876 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007877
Rafael Espindola3ae00052013-05-13 00:12:11 +00007878 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007879 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007880
David Majnemerc3d07332014-05-15 06:25:57 +00007881 // C++11 [temp.explicit]p10:
7882 // [ Note: The intent is that an inline function that is the subject of
7883 // an explicit instantiation declaration will still be implicitly
7884 // instantiated when used so that the body can be considered for
7885 // inlining, but that no out-of-line copy of the inline function would be
7886 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007887 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007888 return GVA_AvailableExternally;
7889
Rafael Espindola3ae00052013-05-13 00:12:11 +00007890 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007891 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007892 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007893 }
7894
7895 if (!FD->isInlined())
7896 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007897
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007898 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7899 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007900 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007901 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7902
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007903 // GNU or C99 inline semantics. Determine whether this symbol should be
7904 // externally visible.
7905 if (FD->isInlineDefinitionExternallyVisible())
7906 return External;
7907
7908 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007909 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007910 }
7911
David Majnemer54e3ba52014-04-02 23:17:29 +00007912 // Functions specified with extern and inline in -fms-compatibility mode
7913 // forcibly get emitted. While the body of the function cannot be later
7914 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00007915 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00007916 return GVA_StrongODR;
7917
David Majnemer27d69db2014-04-28 22:17:59 +00007918 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007919}
7920
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007921static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7922 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7923 // dllexport/dllimport on inline functions.
7924 if (D->hasAttr<DLLImportAttr>()) {
7925 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7926 return GVA_AvailableExternally;
7927 } else if (D->hasAttr<DLLExportAttr>()) {
7928 if (L == GVA_DiscardableODR)
7929 return GVA_StrongODR;
7930 }
7931 return L;
7932}
7933
7934GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7935 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7936 FD);
7937}
7938
7939static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7940 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007941 if (!VD->isExternallyVisible())
7942 return GVA_Internal;
7943
David Majnemer27d69db2014-04-28 22:17:59 +00007944 if (VD->isStaticLocal()) {
7945 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7946 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7947 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7948 LexicalContext = LexicalContext->getLexicalParent();
7949
Richard Smith9e2341d2015-03-23 03:25:59 +00007950 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00007951 // enclosing function.
7952 if (LexicalContext)
7953 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007954 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007955
7956 // GVA_StrongODR function linkage is stronger than what we need,
7957 // downgrade to GVA_DiscardableODR.
7958 // This allows us to discard the variable if we never end up needing it.
7959 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7960 : StaticLocalLinkage;
7961 }
7962
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007963 // MSVC treats in-class initialized static data members as definitions.
7964 // By giving them non-strong linkage, out-of-line definitions won't
7965 // cause link errors.
7966 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7967 return GVA_DiscardableODR;
7968
Richard Smith8809a0c2013-09-27 20:14:12 +00007969 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007970 case TSK_Undeclared:
7971 case TSK_ExplicitSpecialization:
7972 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007973
Rafael Espindola3ae00052013-05-13 00:12:11 +00007974 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007975 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007976
David Majnemer27d69db2014-04-28 22:17:59 +00007977 case TSK_ExplicitInstantiationDeclaration:
7978 return GVA_AvailableExternally;
7979
Rafael Espindola3ae00052013-05-13 00:12:11 +00007980 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007981 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007982 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007983
7984 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007985}
7986
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007987GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7988 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7989 VD);
7990}
7991
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007992bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007993 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7994 if (!VD->isFileVarDecl())
7995 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00007996 // Global named register variables (GNU extension) are never emitted.
7997 if (VD->getStorageClass() == SC_Register)
7998 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007999 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8000 // We never need to emit an uninstantiated function template.
8001 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8002 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008003 } else if (isa<OMPThreadPrivateDecl>(D))
8004 return true;
8005 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008006 return false;
8007
8008 // If this is a member of a class template, we do not need to emit it.
8009 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008010 return false;
8011
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008012 // Weak references don't produce any output by themselves.
8013 if (D->hasAttr<WeakRefAttr>())
8014 return false;
8015
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008016 // Aliases and used decls are required.
8017 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8018 return true;
8019
8020 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8021 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008022 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008023 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008024
8025 // Constructors and destructors are required.
8026 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8027 return true;
8028
John McCall6bd2a892013-01-25 22:31:03 +00008029 // The key function for a class is required. This rule only comes
8030 // into play when inline functions can be key functions, though.
8031 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8032 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8033 const CXXRecordDecl *RD = MD->getParent();
8034 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8035 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8036 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8037 return true;
8038 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008039 }
8040 }
8041
8042 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8043
8044 // static, static inline, always_inline, and extern inline functions can
8045 // always be deferred. Normal inline functions can be deferred in C99/C++.
8046 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008047 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8048 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008049 return false;
8050 return true;
8051 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008052
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008053 const VarDecl *VD = cast<VarDecl>(D);
8054 assert(VD->isFileVarDecl() && "Expected file scoped var");
8055
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008056 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8057 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008058 return false;
8059
Richard Smitha0e5e542012-11-12 21:38:00 +00008060 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008061 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008062 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8063 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008064 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008065
Richard Smitha0e5e542012-11-12 21:38:00 +00008066 // Variables that have destruction with side-effects are required.
8067 if (VD->getType().isDestructedType())
8068 return true;
8069
8070 // Variables that have initialization with side-effects are required.
8071 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8072 return true;
8073
8074 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008075}
Charles Davis53c59df2010-08-16 03:33:14 +00008076
Reid Kleckner78af0702013-08-27 23:08:25 +00008077CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8078 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008079 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008080 if (IsCXXMethod)
8081 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008082
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008083 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8084
8085 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008086}
8087
Jay Foad39c79802011-01-12 09:06:06 +00008088bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008089 // Pass through to the C++ ABI object
8090 return ABI->isNearlyEmpty(RD);
8091}
8092
Reid Kleckner96f8f932014-02-05 17:27:08 +00008093VTableContextBase *ASTContext::getVTableContext() {
8094 if (!VTContext.get()) {
8095 if (Target->getCXXABI().isMicrosoft())
8096 VTContext.reset(new MicrosoftVTableContext(*this));
8097 else
8098 VTContext.reset(new ItaniumVTableContext(*this));
8099 }
8100 return VTContext.get();
8101}
8102
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008103MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008104 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008105 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008106 case TargetCXXABI::GenericItanium:
8107 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008108 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008109 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008110 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008111 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008112 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008113 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008114 }
David Blaikie83d382b2011-09-23 05:06:16 +00008115 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008116}
8117
Charles Davis53c59df2010-08-16 03:33:14 +00008118CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008119
8120size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008121 return ASTRecordLayouts.getMemorySize() +
8122 llvm::capacity_in_bytes(ObjCLayouts) +
8123 llvm::capacity_in_bytes(KeyFunctions) +
8124 llvm::capacity_in_bytes(ObjCImpls) +
8125 llvm::capacity_in_bytes(BlockVarCopyInits) +
8126 llvm::capacity_in_bytes(DeclAttrs) +
8127 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8128 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8129 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8130 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8131 llvm::capacity_in_bytes(OverriddenMethods) +
8132 llvm::capacity_in_bytes(Types) +
8133 llvm::capacity_in_bytes(VariableArrayTypes) +
8134 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008135}
Ted Kremenek540017e2011-10-06 05:00:56 +00008136
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008137/// getIntTypeForBitwidth -
8138/// sets integer QualTy according to specified details:
8139/// bitwidth, signed/unsigned.
8140/// Returns empty type if there is no appropriate target types.
8141QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8142 unsigned Signed) const {
8143 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8144 CanQualType QualTy = getFromTargetType(Ty);
8145 if (!QualTy && DestWidth == 128)
8146 return Signed ? Int128Ty : UnsignedInt128Ty;
8147 return QualTy;
8148}
8149
8150/// getRealTypeForBitwidth -
8151/// sets floating point QualTy according to specified bitwidth.
8152/// Returns empty type if there is no appropriate target types.
8153QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8154 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8155 switch (Ty) {
8156 case TargetInfo::Float:
8157 return FloatTy;
8158 case TargetInfo::Double:
8159 return DoubleTy;
8160 case TargetInfo::LongDouble:
8161 return LongDoubleTy;
8162 case TargetInfo::NoFloat:
8163 return QualType();
8164 }
8165
8166 llvm_unreachable("Unhandled TargetInfo::RealType value");
8167}
8168
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008169void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8170 if (Number > 1)
8171 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008172}
8173
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008174unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8175 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8176 MangleNumbers.find(ND);
8177 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008178}
8179
David Majnemer2206bf52014-03-05 08:57:59 +00008180void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8181 if (Number > 1)
8182 StaticLocalNumbers[VD] = Number;
8183}
8184
8185unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8186 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8187 StaticLocalNumbers.find(VD);
8188 return I != StaticLocalNumbers.end() ? I->second : 1;
8189}
8190
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008191MangleNumberingContext &
8192ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008193 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8194 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8195 if (!MCtx)
8196 MCtx = createMangleNumberingContext();
8197 return *MCtx;
8198}
8199
8200MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8201 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008202}
8203
David Majnemere7a818f2015-03-06 18:53:55 +00008204const CXXConstructorDecl *
8205ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8206 return ABI->getCopyConstructorForExceptionObject(
8207 cast<CXXRecordDecl>(RD->getFirstDecl()));
8208}
8209
8210void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8211 CXXConstructorDecl *CD) {
8212 return ABI->addCopyConstructorForExceptionObject(
8213 cast<CXXRecordDecl>(RD->getFirstDecl()),
8214 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8215}
8216
David Majnemerdfa6d202015-03-11 18:36:39 +00008217void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8218 unsigned ParmIdx, Expr *DAE) {
8219 ABI->addDefaultArgExprForConstructor(
8220 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8221}
8222
8223Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8224 unsigned ParmIdx) {
8225 return ABI->getDefaultArgExprForConstructor(
8226 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8227}
8228
Ted Kremenek540017e2011-10-06 05:00:56 +00008229void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8230 ParamIndices[D] = index;
8231}
8232
8233unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8234 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8235 assert(I != ParamIndices.end() &&
8236 "ParmIndices lacks entry set by ParmVarDecl");
8237 return I->second;
8238}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008239
Richard Smithe6c01442013-06-05 00:46:14 +00008240APValue *
8241ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8242 bool MayCreate) {
8243 assert(E && E->getStorageDuration() == SD_Static &&
8244 "don't need to cache the computed value for this temporary");
8245 if (MayCreate)
8246 return &MaterializedTemporaryValues[E];
8247
8248 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8249 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008250 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008251}
8252
Fariborz Jahanian615de762013-05-28 17:37:39 +00008253bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8254 const llvm::Triple &T = getTargetInfo().getTriple();
8255 if (!T.isOSDarwin())
8256 return false;
8257
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008258 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8259 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8260 return false;
8261
Fariborz Jahanian615de762013-05-28 17:37:39 +00008262 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8263 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8264 uint64_t Size = sizeChars.getQuantity();
8265 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8266 unsigned Align = alignChars.getQuantity();
8267 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8268 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8269}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008270
8271namespace {
8272
8273 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8274 /// parents as defined by the \c RecursiveASTVisitor.
8275 ///
8276 /// Note that the relationship described here is purely in terms of AST
8277 /// traversal - there are other relationships (for example declaration context)
8278 /// in the AST that are better modeled by special matchers.
8279 ///
8280 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8281 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8282
8283 public:
8284 /// \brief Builds and returns the translation unit's parent map.
8285 ///
8286 /// The caller takes ownership of the returned \c ParentMap.
8287 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8288 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8289 Visitor.TraverseDecl(&TU);
8290 return Visitor.Parents;
8291 }
8292
8293 private:
8294 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8295
8296 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8297 }
8298
8299 bool shouldVisitTemplateInstantiations() const {
8300 return true;
8301 }
8302 bool shouldVisitImplicitCode() const {
8303 return true;
8304 }
8305 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8306 // are not triggered during data recursion.
8307 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8308 return false;
8309 }
8310
8311 template <typename T>
8312 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008313 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008314 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008315 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008316 // FIXME: Currently we add the same parent multiple times, but only
8317 // when no memoization data is available for the type.
8318 // For example when we visit all subexpressions of template
8319 // instantiations; this is suboptimal, but benign: the only way to
8320 // visit those is with hasAncestor / hasParent, and those do not create
8321 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008322 // The plan is to enable DynTypedNode to be storable in a map or hash
8323 // map. The main problem there is to implement hash functions /
8324 // comparison operators for all types that DynTypedNode supports that
8325 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008326 auto &NodeOrVector = (*Parents)[Node];
8327 if (NodeOrVector.isNull()) {
8328 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008329 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008330 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8331 auto *Node =
8332 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8333 auto *Vector = new ASTContext::ParentVector(1, *Node);
8334 NodeOrVector = Vector;
8335 delete Node;
8336 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008337 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008338
8339 auto *Vector =
8340 NodeOrVector.template get<ASTContext::ParentVector *>();
8341 // Skip duplicates for types that have memoization data.
8342 // We must check that the type has memoization data before calling
8343 // std::find() because DynTypedNode::operator== can't compare all
8344 // types.
8345 bool Found = ParentStack.back().getMemoizationData() &&
8346 std::find(Vector->begin(), Vector->end(),
8347 ParentStack.back()) != Vector->end();
8348 if (!Found)
8349 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008350 }
8351 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008352 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8353 bool Result = (this ->* traverse) (Node);
8354 ParentStack.pop_back();
8355 return Result;
8356 }
8357
8358 bool TraverseDecl(Decl *DeclNode) {
8359 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8360 }
8361
8362 bool TraverseStmt(Stmt *StmtNode) {
8363 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8364 }
8365
8366 ASTContext::ParentMap *Parents;
8367 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8368
8369 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8370 };
8371
8372} // end namespace
8373
Benjamin Kramer07935292014-10-04 17:01:26 +00008374ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008375ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8376 assert(Node.getMemoizationData() &&
8377 "Invariant broken: only nodes that support memoization may be "
8378 "used in the parent map.");
8379 if (!AllParents) {
8380 // We always need to run over the whole translation unit, as
8381 // hasAncestor can escape any subtree.
8382 AllParents.reset(
8383 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8384 }
8385 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8386 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008387 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008388 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008389 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8390 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008391 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008392 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008393}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008394
8395bool
8396ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8397 const ObjCMethodDecl *MethodImpl) {
8398 // No point trying to match an unavailable/deprecated mothod.
8399 if (MethodDecl->hasAttr<UnavailableAttr>()
8400 || MethodDecl->hasAttr<DeprecatedAttr>())
8401 return false;
8402 if (MethodDecl->getObjCDeclQualifier() !=
8403 MethodImpl->getObjCDeclQualifier())
8404 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008405 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008406 return false;
8407
8408 if (MethodDecl->param_size() != MethodImpl->param_size())
8409 return false;
8410
8411 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8412 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8413 EF = MethodDecl->param_end();
8414 IM != EM && IF != EF; ++IM, ++IF) {
8415 const ParmVarDecl *DeclVar = (*IF);
8416 const ParmVarDecl *ImplVar = (*IM);
8417 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8418 return false;
8419 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8420 return false;
8421 }
8422 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8423
8424}
Richard Smith053f6c62014-05-16 23:01:30 +00008425
8426// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8427// doesn't include ASTContext.h
8428template
8429clang::LazyGenerationalUpdatePtr<
8430 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8431clang::LazyGenerationalUpdatePtr<
8432 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8433 const clang::ASTContext &Ctx, Decl *Value);