blob: 4d6a51bf1924196a7d189aaf6ff137c66bd8ee87 [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 Weigandca3cb7f2015-04-21 17:29:35 +00001820/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1821/// for __attribute__((aligned)) on this target, to be used if no alignment
1822/// value is specified.
1823unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1824 return getTargetInfo().getDefaultAlignForAttributeAligned();
1825}
1826
Ulrich Weigandfa806422013-05-06 16:23:57 +00001827/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1828/// to a global variable of the specified type.
1829unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1830 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1831}
1832
1833/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1834/// should be given to a global variable of the specified type.
1835CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1836 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1837}
1838
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001839/// DeepCollectObjCIvars -
1840/// This routine first collects all declared, but not synthesized, ivars in
1841/// super class and then collects all ivars, including those synthesized for
1842/// current class. This routine is used for implementation of current class
1843/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001844///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001845void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1846 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001847 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001848 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1849 DeepCollectObjCIvars(SuperClass, false, Ivars);
1850 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001851 for (const auto *I : OI->ivars())
1852 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001853 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001854 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001855 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001856 Iv= Iv->getNextIvar())
1857 Ivars.push_back(Iv);
1858 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001859}
1860
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001861/// CollectInheritedProtocols - Collect all protocols in current class and
1862/// those inherited by it.
1863void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001864 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001865 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001866 // We can use protocol_iterator here instead of
1867 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001868 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001869 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001870 for (auto *P : Proto->protocols()) {
1871 Protocols.insert(P->getCanonicalDecl());
1872 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001873 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001874 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001875
1876 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001877 for (const auto *Cat : OI->visible_categories())
1878 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001879
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001880 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1881 while (SD) {
1882 CollectInheritedProtocols(SD, Protocols);
1883 SD = SD->getSuperClass();
1884 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001885 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001886 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001887 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001888 for (const auto *P : Proto->protocols())
1889 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001890 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001891 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001892 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001893 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001894 for (const auto *P : Proto->protocols())
1895 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001896 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001897 }
1898}
1899
Jay Foad39c79802011-01-12 09:06:06 +00001900unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001901 unsigned count = 0;
1902 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001903 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001904 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001905
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001906 // Count ivar defined in this class's implementation. This
1907 // includes synthesized ivars.
1908 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001909 count += ImplDecl->ivar_size();
1910
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001911 return count;
1912}
1913
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001914bool ASTContext::isSentinelNullExpr(const Expr *E) {
1915 if (!E)
1916 return false;
1917
1918 // nullptr_t is always treated as null.
1919 if (E->getType()->isNullPtrType()) return true;
1920
1921 if (E->getType()->isAnyPointerType() &&
1922 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1923 Expr::NPC_ValueDependentIsNull))
1924 return true;
1925
1926 // Unfortunately, __null has type 'int'.
1927 if (isa<GNUNullExpr>(E)) return true;
1928
1929 return false;
1930}
1931
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001932/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1933ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1934 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1935 I = ObjCImpls.find(D);
1936 if (I != ObjCImpls.end())
1937 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001938 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001939}
1940/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1941ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1942 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1943 I = ObjCImpls.find(D);
1944 if (I != ObjCImpls.end())
1945 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001946 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001947}
1948
1949/// \brief Set the implementation of ObjCInterfaceDecl.
1950void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1951 ObjCImplementationDecl *ImplD) {
1952 assert(IFaceD && ImplD && "Passed null params");
1953 ObjCImpls[IFaceD] = ImplD;
1954}
1955/// \brief Set the implementation of ObjCCategoryDecl.
1956void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1957 ObjCCategoryImplDecl *ImplD) {
1958 assert(CatD && ImplD && "Passed null params");
1959 ObjCImpls[CatD] = ImplD;
1960}
1961
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001962const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1963 const NamedDecl *ND) const {
1964 if (const ObjCInterfaceDecl *ID =
1965 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001966 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001967 if (const ObjCCategoryDecl *CD =
1968 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001969 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001970 if (const ObjCImplDecl *IMD =
1971 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001972 return IMD->getClassInterface();
1973
Craig Topper36250ad2014-05-12 05:36:57 +00001974 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001975}
1976
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001977/// \brief Get the copy initialization expression of VarDecl,or NULL if
1978/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001979Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001980 assert(VD && "Passed null params");
1981 assert(VD->hasAttr<BlocksAttr>() &&
1982 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001983 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001984 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001985 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001986}
1987
1988/// \brief Set the copy inialization expression of a block var decl.
1989void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1990 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001991 assert(VD->hasAttr<BlocksAttr>() &&
1992 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001993 BlockVarCopyInits[VD] = Init;
1994}
1995
John McCallbcd03502009-12-07 02:54:59 +00001996TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001997 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001998 if (!DataSize)
1999 DataSize = TypeLoc::getFullDataSizeForType(T);
2000 else
2001 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002002 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002003
John McCallbcd03502009-12-07 02:54:59 +00002004 TypeSourceInfo *TInfo =
2005 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2006 new (TInfo) TypeSourceInfo(T);
2007 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002008}
2009
John McCallbcd03502009-12-07 02:54:59 +00002010TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002011 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002012 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002013 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002014 return DI;
2015}
2016
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002017const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002018ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002019 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002020}
2021
2022const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002023ASTContext::getASTObjCImplementationLayout(
2024 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002025 return getObjCLayout(D->getClassInterface(), D);
2026}
2027
Chris Lattner983a8bb2007-07-13 22:13:22 +00002028//===----------------------------------------------------------------------===//
2029// Type creation/memoization methods
2030//===----------------------------------------------------------------------===//
2031
Jay Foad39c79802011-01-12 09:06:06 +00002032QualType
John McCall33ddac02011-01-19 10:06:00 +00002033ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2034 unsigned fastQuals = quals.getFastQualifiers();
2035 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002036
2037 // Check if we've already instantiated this type.
2038 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002039 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002040 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002041 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2042 assert(eq->getQualifiers() == quals);
2043 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002044 }
2045
John McCall33ddac02011-01-19 10:06:00 +00002046 // If the base type is not canonical, make the appropriate canonical type.
2047 QualType canon;
2048 if (!baseType->isCanonicalUnqualified()) {
2049 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002050 canonSplit.Quals.addConsistentQualifiers(quals);
2051 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002052
2053 // Re-find the insert position.
2054 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2055 }
2056
2057 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2058 ExtQualNodes.InsertNode(eq, insertPos);
2059 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002060}
2061
Jay Foad39c79802011-01-12 09:06:06 +00002062QualType
2063ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002064 QualType CanT = getCanonicalType(T);
2065 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002066 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002067
John McCall8ccfcb52009-09-24 19:53:00 +00002068 // If we are composing extended qualifiers together, merge together
2069 // into one ExtQuals node.
2070 QualifierCollector Quals;
2071 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002072
John McCall8ccfcb52009-09-24 19:53:00 +00002073 // If this type already has an address space specified, it cannot get
2074 // another one.
2075 assert(!Quals.hasAddressSpace() &&
2076 "Type cannot be in multiple addr spaces!");
2077 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002078
John McCall8ccfcb52009-09-24 19:53:00 +00002079 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002080}
2081
Chris Lattnerd60183d2009-02-18 22:53:11 +00002082QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002083 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002084 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002085 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002086 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002087
John McCall53fa7142010-12-24 02:08:15 +00002088 if (const PointerType *ptr = T->getAs<PointerType>()) {
2089 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002090 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002091 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2092 return getPointerType(ResultType);
2093 }
2094 }
Mike Stump11289f42009-09-09 15:08:12 +00002095
John McCall8ccfcb52009-09-24 19:53:00 +00002096 // If we are composing extended qualifiers together, merge together
2097 // into one ExtQuals node.
2098 QualifierCollector Quals;
2099 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002100
John McCall8ccfcb52009-09-24 19:53:00 +00002101 // If this type already has an ObjCGC specified, it cannot get
2102 // another one.
2103 assert(!Quals.hasObjCGCAttr() &&
2104 "Type cannot have multiple ObjCGCs!");
2105 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002106
John McCall8ccfcb52009-09-24 19:53:00 +00002107 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002108}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002109
John McCall4f5019e2010-12-19 02:44:49 +00002110const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2111 FunctionType::ExtInfo Info) {
2112 if (T->getExtInfo() == Info)
2113 return T;
2114
2115 QualType Result;
2116 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002117 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002118 } else {
2119 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2120 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2121 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002122 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002123 }
2124
2125 return cast<FunctionType>(Result.getTypePtr());
2126}
2127
Richard Smith2a7d4812013-05-04 07:00:32 +00002128void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2129 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002130 FD = FD->getMostRecentDecl();
2131 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002132 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2133 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002134 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002135 if (FunctionDecl *Next = FD->getPreviousDecl())
2136 FD = Next;
2137 else
2138 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002139 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002140 if (ASTMutationListener *L = getASTMutationListener())
2141 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002142}
2143
Richard Smith0b3a4622014-11-13 20:01:57 +00002144/// Get a function type and produce the equivalent function type with the
2145/// specified exception specification. Type sugar that can be present on a
2146/// declaration of a function with an exception specification is permitted
2147/// and preserved. Other type sugar (for instance, typedefs) is not.
2148static QualType getFunctionTypeWithExceptionSpec(
2149 ASTContext &Context, QualType Orig,
2150 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2151 // Might have some parens.
2152 if (auto *PT = dyn_cast<ParenType>(Orig))
2153 return Context.getParenType(
2154 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2155
2156 // Might have a calling-convention attribute.
2157 if (auto *AT = dyn_cast<AttributedType>(Orig))
2158 return Context.getAttributedType(
2159 AT->getAttrKind(),
2160 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2161 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2162 ESI));
2163
2164 // Anything else must be a function type. Rebuild it with the new exception
2165 // specification.
2166 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2167 return Context.getFunctionType(
2168 Proto->getReturnType(), Proto->getParamTypes(),
2169 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2170}
2171
2172void ASTContext::adjustExceptionSpec(
2173 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2174 bool AsWritten) {
2175 // Update the type.
2176 QualType Updated =
2177 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2178 FD->setType(Updated);
2179
2180 if (!AsWritten)
2181 return;
2182
2183 // Update the type in the type source information too.
2184 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2185 // If the type and the type-as-written differ, we may need to update
2186 // the type-as-written too.
2187 if (TSInfo->getType() != FD->getType())
2188 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2189
2190 // FIXME: When we get proper type location information for exceptions,
2191 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2192 // up the TypeSourceInfo;
2193 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2194 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2195 "TypeLoc size mismatch from updating exception specification");
2196 TSInfo->overrideType(Updated);
2197 }
2198}
2199
Chris Lattnerc6395932007-06-22 20:56:16 +00002200/// getComplexType - Return the uniqued reference to the type for a complex
2201/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002202QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002203 // Unique pointers, to guarantee there is only one pointer of a particular
2204 // structure.
2205 llvm::FoldingSetNodeID ID;
2206 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002207
Craig Topper36250ad2014-05-12 05:36:57 +00002208 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002209 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2210 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002211
Chris Lattnerc6395932007-06-22 20:56:16 +00002212 // If the pointee type isn't canonical, this won't be a canonical type either,
2213 // so fill in the canonical type field.
2214 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002215 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002216 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002217
Chris Lattnerc6395932007-06-22 20:56:16 +00002218 // Get the new insert position for the node we care about.
2219 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002220 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002221 }
John McCall90d1c2d2009-09-24 23:30:46 +00002222 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002223 Types.push_back(New);
2224 ComplexTypes.InsertNode(New, InsertPos);
2225 return QualType(New, 0);
2226}
2227
Chris Lattner970e54e2006-11-12 00:37:36 +00002228/// getPointerType - Return the uniqued reference to the type for a pointer to
2229/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002230QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002231 // Unique pointers, to guarantee there is only one pointer of a particular
2232 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002233 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002234 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002235
Craig Topper36250ad2014-05-12 05:36:57 +00002236 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002237 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002238 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002239
Chris Lattner7ccecb92006-11-12 08:50:50 +00002240 // If the pointee type isn't canonical, this won't be a canonical type either,
2241 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002242 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002243 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002244 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002245
Bob Wilsonc8541f22013-03-15 17:12:43 +00002246 // Get the new insert position for the node we care about.
2247 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002248 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002249 }
John McCall90d1c2d2009-09-24 23:30:46 +00002250 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002251 Types.push_back(New);
2252 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002253 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002254}
2255
Reid Kleckner0503a872013-12-05 01:23:43 +00002256QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2257 llvm::FoldingSetNodeID ID;
2258 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002259 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002260 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2261 if (AT)
2262 return QualType(AT, 0);
2263
2264 QualType Canonical = getCanonicalType(New);
2265
2266 // Get the new insert position for the node we care about.
2267 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002268 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002269
2270 AT = new (*this, TypeAlignment)
2271 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2272 Types.push_back(AT);
2273 AdjustedTypes.InsertNode(AT, InsertPos);
2274 return QualType(AT, 0);
2275}
2276
Reid Kleckner8a365022013-06-24 17:51:48 +00002277QualType ASTContext::getDecayedType(QualType T) const {
2278 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2279
Reid Kleckner8a365022013-06-24 17:51:48 +00002280 QualType Decayed;
2281
2282 // C99 6.7.5.3p7:
2283 // A declaration of a parameter as "array of type" shall be
2284 // adjusted to "qualified pointer to type", where the type
2285 // qualifiers (if any) are those specified within the [ and ] of
2286 // the array type derivation.
2287 if (T->isArrayType())
2288 Decayed = getArrayDecayedType(T);
2289
2290 // C99 6.7.5.3p8:
2291 // A declaration of a parameter as "function returning type"
2292 // shall be adjusted to "pointer to function returning type", as
2293 // in 6.3.2.1.
2294 if (T->isFunctionType())
2295 Decayed = getPointerType(T);
2296
Reid Kleckner0503a872013-12-05 01:23:43 +00002297 llvm::FoldingSetNodeID ID;
2298 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002299 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002300 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2301 if (AT)
2302 return QualType(AT, 0);
2303
Reid Kleckner8a365022013-06-24 17:51:48 +00002304 QualType Canonical = getCanonicalType(Decayed);
2305
2306 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002307 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002308 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002309
Reid Kleckner0503a872013-12-05 01:23:43 +00002310 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2311 Types.push_back(AT);
2312 AdjustedTypes.InsertNode(AT, InsertPos);
2313 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002314}
2315
Mike Stump11289f42009-09-09 15:08:12 +00002316/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002317/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002318QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002319 assert(T->isFunctionType() && "block of function types only");
2320 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002321 // structure.
2322 llvm::FoldingSetNodeID ID;
2323 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002324
Craig Topper36250ad2014-05-12 05:36:57 +00002325 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002326 if (BlockPointerType *PT =
2327 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2328 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002329
2330 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002331 // type either so fill in the canonical type field.
2332 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002333 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002334 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002335
Steve Naroffec33ed92008-08-27 16:04:49 +00002336 // Get the new insert position for the node we care about.
2337 BlockPointerType *NewIP =
2338 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002339 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002340 }
John McCall90d1c2d2009-09-24 23:30:46 +00002341 BlockPointerType *New
2342 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002343 Types.push_back(New);
2344 BlockPointerTypes.InsertNode(New, InsertPos);
2345 return QualType(New, 0);
2346}
2347
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002348/// getLValueReferenceType - Return the uniqued reference to the type for an
2349/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002350QualType
2351ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002352 assert(getCanonicalType(T) != OverloadTy &&
2353 "Unresolved overloaded function type");
2354
Bill Wendling3708c182007-05-27 10:15:43 +00002355 // Unique pointers, to guarantee there is only one pointer of a particular
2356 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002357 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002358 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002359
Craig Topper36250ad2014-05-12 05:36:57 +00002360 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002361 if (LValueReferenceType *RT =
2362 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002363 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002364
John McCallfc93cf92009-10-22 22:37:11 +00002365 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2366
Bill Wendling3708c182007-05-27 10:15:43 +00002367 // If the referencee type isn't canonical, this won't be a canonical type
2368 // either, so fill in the canonical type field.
2369 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002370 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2371 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2372 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002373
Bill Wendling3708c182007-05-27 10:15:43 +00002374 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002375 LValueReferenceType *NewIP =
2376 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002377 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002378 }
2379
John McCall90d1c2d2009-09-24 23:30:46 +00002380 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002381 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2382 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002383 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002384 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002385
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002386 return QualType(New, 0);
2387}
2388
2389/// getRValueReferenceType - Return the uniqued reference to the type for an
2390/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002391QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002392 // Unique pointers, to guarantee there is only one pointer of a particular
2393 // structure.
2394 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002395 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002396
Craig Topper36250ad2014-05-12 05:36:57 +00002397 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002398 if (RValueReferenceType *RT =
2399 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2400 return QualType(RT, 0);
2401
John McCallfc93cf92009-10-22 22:37:11 +00002402 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2403
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002404 // If the referencee type isn't canonical, this won't be a canonical type
2405 // either, so fill in the canonical type field.
2406 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002407 if (InnerRef || !T.isCanonical()) {
2408 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2409 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002410
2411 // Get the new insert position for the node we care about.
2412 RValueReferenceType *NewIP =
2413 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002414 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002415 }
2416
John McCall90d1c2d2009-09-24 23:30:46 +00002417 RValueReferenceType *New
2418 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002419 Types.push_back(New);
2420 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002421 return QualType(New, 0);
2422}
2423
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002424/// getMemberPointerType - Return the uniqued reference to the type for a
2425/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002426QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002427 // Unique pointers, to guarantee there is only one pointer of a particular
2428 // structure.
2429 llvm::FoldingSetNodeID ID;
2430 MemberPointerType::Profile(ID, T, Cls);
2431
Craig Topper36250ad2014-05-12 05:36:57 +00002432 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002433 if (MemberPointerType *PT =
2434 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2435 return QualType(PT, 0);
2436
2437 // If the pointee or class type isn't canonical, this won't be a canonical
2438 // type either, so fill in the canonical type field.
2439 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002440 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002441 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2442
2443 // Get the new insert position for the node we care about.
2444 MemberPointerType *NewIP =
2445 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002446 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002447 }
John McCall90d1c2d2009-09-24 23:30:46 +00002448 MemberPointerType *New
2449 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002450 Types.push_back(New);
2451 MemberPointerTypes.InsertNode(New, InsertPos);
2452 return QualType(New, 0);
2453}
2454
Mike Stump11289f42009-09-09 15:08:12 +00002455/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002456/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002457QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002458 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002459 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002460 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002461 assert((EltTy->isDependentType() ||
2462 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002463 "Constant array of VLAs is illegal!");
2464
Chris Lattnere2df3f92009-05-13 04:12:56 +00002465 // Convert the array size into a canonical width matching the pointer size for
2466 // the target.
2467 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002468 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002469 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002470
Chris Lattner23b7eb62007-06-15 23:05:46 +00002471 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002472 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002473
Craig Topper36250ad2014-05-12 05:36:57 +00002474 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002475 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002476 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002477 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002478
John McCall33ddac02011-01-19 10:06:00 +00002479 // If the element type isn't canonical or has qualifiers, this won't
2480 // be a canonical type either, so fill in the canonical type field.
2481 QualType Canon;
2482 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2483 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002484 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002485 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002486 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002487
Chris Lattner36f8e652007-01-27 08:31:04 +00002488 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002489 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002490 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002491 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002492 }
Mike Stump11289f42009-09-09 15:08:12 +00002493
John McCall90d1c2d2009-09-24 23:30:46 +00002494 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002495 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002496 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002497 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002498 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002499}
2500
John McCall06549462011-01-18 08:40:38 +00002501/// getVariableArrayDecayedType - Turns the given type, which may be
2502/// variably-modified, into the corresponding type with all the known
2503/// sizes replaced with [*].
2504QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2505 // Vastly most common case.
2506 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002507
John McCall06549462011-01-18 08:40:38 +00002508 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002509
John McCall06549462011-01-18 08:40:38 +00002510 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002511 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002512 switch (ty->getTypeClass()) {
2513#define TYPE(Class, Base)
2514#define ABSTRACT_TYPE(Class, Base)
2515#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2516#include "clang/AST/TypeNodes.def"
2517 llvm_unreachable("didn't desugar past all non-canonical types?");
2518
2519 // These types should never be variably-modified.
2520 case Type::Builtin:
2521 case Type::Complex:
2522 case Type::Vector:
2523 case Type::ExtVector:
2524 case Type::DependentSizedExtVector:
2525 case Type::ObjCObject:
2526 case Type::ObjCInterface:
2527 case Type::ObjCObjectPointer:
2528 case Type::Record:
2529 case Type::Enum:
2530 case Type::UnresolvedUsing:
2531 case Type::TypeOfExpr:
2532 case Type::TypeOf:
2533 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002534 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002535 case Type::DependentName:
2536 case Type::InjectedClassName:
2537 case Type::TemplateSpecialization:
2538 case Type::DependentTemplateSpecialization:
2539 case Type::TemplateTypeParm:
2540 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002541 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002542 case Type::PackExpansion:
2543 llvm_unreachable("type should never be variably-modified");
2544
2545 // These types can be variably-modified but should never need to
2546 // further decay.
2547 case Type::FunctionNoProto:
2548 case Type::FunctionProto:
2549 case Type::BlockPointer:
2550 case Type::MemberPointer:
2551 return type;
2552
2553 // These types can be variably-modified. All these modifications
2554 // preserve structure except as noted by comments.
2555 // TODO: if we ever care about optimizing VLAs, there are no-op
2556 // optimizations available here.
2557 case Type::Pointer:
2558 result = getPointerType(getVariableArrayDecayedType(
2559 cast<PointerType>(ty)->getPointeeType()));
2560 break;
2561
2562 case Type::LValueReference: {
2563 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2564 result = getLValueReferenceType(
2565 getVariableArrayDecayedType(lv->getPointeeType()),
2566 lv->isSpelledAsLValue());
2567 break;
2568 }
2569
2570 case Type::RValueReference: {
2571 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2572 result = getRValueReferenceType(
2573 getVariableArrayDecayedType(lv->getPointeeType()));
2574 break;
2575 }
2576
Eli Friedman0dfb8892011-10-06 23:00:33 +00002577 case Type::Atomic: {
2578 const AtomicType *at = cast<AtomicType>(ty);
2579 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2580 break;
2581 }
2582
John McCall06549462011-01-18 08:40:38 +00002583 case Type::ConstantArray: {
2584 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2585 result = getConstantArrayType(
2586 getVariableArrayDecayedType(cat->getElementType()),
2587 cat->getSize(),
2588 cat->getSizeModifier(),
2589 cat->getIndexTypeCVRQualifiers());
2590 break;
2591 }
2592
2593 case Type::DependentSizedArray: {
2594 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2595 result = getDependentSizedArrayType(
2596 getVariableArrayDecayedType(dat->getElementType()),
2597 dat->getSizeExpr(),
2598 dat->getSizeModifier(),
2599 dat->getIndexTypeCVRQualifiers(),
2600 dat->getBracketsRange());
2601 break;
2602 }
2603
2604 // Turn incomplete types into [*] types.
2605 case Type::IncompleteArray: {
2606 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2607 result = getVariableArrayType(
2608 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002609 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002610 ArrayType::Normal,
2611 iat->getIndexTypeCVRQualifiers(),
2612 SourceRange());
2613 break;
2614 }
2615
2616 // Turn VLA types into [*] types.
2617 case Type::VariableArray: {
2618 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2619 result = getVariableArrayType(
2620 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002621 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002622 ArrayType::Star,
2623 vat->getIndexTypeCVRQualifiers(),
2624 vat->getBracketsRange());
2625 break;
2626 }
2627 }
2628
2629 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002630 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002631}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002632
Steve Naroffcadebd02007-08-30 18:14:25 +00002633/// getVariableArrayType - Returns a non-unique reference to the type for a
2634/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002635QualType ASTContext::getVariableArrayType(QualType EltTy,
2636 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002637 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002638 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002639 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002640 // Since we don't unique expressions, it isn't possible to unique VLA's
2641 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002642 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002643
John McCall33ddac02011-01-19 10:06:00 +00002644 // Be sure to pull qualifiers off the element type.
2645 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2646 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002647 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002648 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002649 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002650 }
2651
John McCall90d1c2d2009-09-24 23:30:46 +00002652 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002653 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002654
2655 VariableArrayTypes.push_back(New);
2656 Types.push_back(New);
2657 return QualType(New, 0);
2658}
2659
Douglas Gregor4619e432008-12-05 23:32:09 +00002660/// getDependentSizedArrayType - Returns a non-unique reference to
2661/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002662/// type.
John McCall33ddac02011-01-19 10:06:00 +00002663QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2664 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002665 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002666 unsigned elementTypeQuals,
2667 SourceRange brackets) const {
2668 assert((!numElements || numElements->isTypeDependent() ||
2669 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002670 "Size must be type- or value-dependent!");
2671
John McCall33ddac02011-01-19 10:06:00 +00002672 // Dependently-sized array types that do not have a specified number
2673 // of elements will have their sizes deduced from a dependent
2674 // initializer. We do no canonicalization here at all, which is okay
2675 // because they can't be used in most locations.
2676 if (!numElements) {
2677 DependentSizedArrayType *newType
2678 = new (*this, TypeAlignment)
2679 DependentSizedArrayType(*this, elementType, QualType(),
2680 numElements, ASM, elementTypeQuals,
2681 brackets);
2682 Types.push_back(newType);
2683 return QualType(newType, 0);
2684 }
2685
2686 // Otherwise, we actually build a new type every time, but we
2687 // also build a canonical type.
2688
2689 SplitQualType canonElementType = getCanonicalType(elementType).split();
2690
Craig Topper36250ad2014-05-12 05:36:57 +00002691 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002692 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002693 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002694 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002695 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002696
John McCall33ddac02011-01-19 10:06:00 +00002697 // Look for an existing type with these properties.
2698 DependentSizedArrayType *canonTy =
2699 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002700
John McCall33ddac02011-01-19 10:06:00 +00002701 // If we don't have one, build one.
2702 if (!canonTy) {
2703 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002704 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002705 QualType(), numElements, ASM, elementTypeQuals,
2706 brackets);
2707 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2708 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002709 }
2710
John McCall33ddac02011-01-19 10:06:00 +00002711 // Apply qualifiers from the element type to the array.
2712 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002713 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002714
John McCall33ddac02011-01-19 10:06:00 +00002715 // If we didn't need extra canonicalization for the element type,
2716 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002717 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002718 return canon;
2719
2720 // Otherwise, we need to build a type which follows the spelling
2721 // of the element type.
2722 DependentSizedArrayType *sugaredType
2723 = new (*this, TypeAlignment)
2724 DependentSizedArrayType(*this, elementType, canon, numElements,
2725 ASM, elementTypeQuals, brackets);
2726 Types.push_back(sugaredType);
2727 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002728}
2729
John McCall33ddac02011-01-19 10:06:00 +00002730QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002731 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002732 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002733 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002734 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002735
Craig Topper36250ad2014-05-12 05:36:57 +00002736 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002737 if (IncompleteArrayType *iat =
2738 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2739 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002740
2741 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002742 // either, so fill in the canonical type field. We also have to pull
2743 // qualifiers off the element type.
2744 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002745
John McCall33ddac02011-01-19 10:06:00 +00002746 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2747 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002748 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002749 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002750 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002751
2752 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002753 IncompleteArrayType *existing =
2754 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2755 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002756 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002757
John McCall33ddac02011-01-19 10:06:00 +00002758 IncompleteArrayType *newType = new (*this, TypeAlignment)
2759 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002760
John McCall33ddac02011-01-19 10:06:00 +00002761 IncompleteArrayTypes.InsertNode(newType, insertPos);
2762 Types.push_back(newType);
2763 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002764}
2765
Steve Naroff91fcddb2007-07-18 18:00:27 +00002766/// getVectorType - Return the unique reference to a vector type of
2767/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002768QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002769 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002770 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002771
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002772 // Check if we've already instantiated a vector of this type.
2773 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002774 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002775
Craig Topper36250ad2014-05-12 05:36:57 +00002776 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002777 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2778 return QualType(VTP, 0);
2779
2780 // If the element type isn't canonical, this won't be a canonical type either,
2781 // so fill in the canonical type field.
2782 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002783 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002784 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002785
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002786 // Get the new insert position for the node we care about.
2787 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002788 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002789 }
John McCall90d1c2d2009-09-24 23:30:46 +00002790 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002791 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002792 VectorTypes.InsertNode(New, InsertPos);
2793 Types.push_back(New);
2794 return QualType(New, 0);
2795}
2796
Nate Begemance4d7fc2008-04-18 23:10:10 +00002797/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002798/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002799QualType
2800ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002801 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002802
Steve Naroff91fcddb2007-07-18 18:00:27 +00002803 // Check if we've already instantiated a vector of this type.
2804 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002805 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002806 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002807 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002808 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2809 return QualType(VTP, 0);
2810
2811 // If the element type isn't canonical, this won't be a canonical type either,
2812 // so fill in the canonical type field.
2813 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002814 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002815 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002816
Steve Naroff91fcddb2007-07-18 18:00:27 +00002817 // Get the new insert position for the node we care about.
2818 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002819 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002820 }
John McCall90d1c2d2009-09-24 23:30:46 +00002821 ExtVectorType *New = new (*this, TypeAlignment)
2822 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002823 VectorTypes.InsertNode(New, InsertPos);
2824 Types.push_back(New);
2825 return QualType(New, 0);
2826}
2827
Jay Foad39c79802011-01-12 09:06:06 +00002828QualType
2829ASTContext::getDependentSizedExtVectorType(QualType vecType,
2830 Expr *SizeExpr,
2831 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002832 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002833 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002834 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002835
Craig Topper36250ad2014-05-12 05:36:57 +00002836 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002837 DependentSizedExtVectorType *Canon
2838 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2839 DependentSizedExtVectorType *New;
2840 if (Canon) {
2841 // We already have a canonical version of this array type; use it as
2842 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002843 New = new (*this, TypeAlignment)
2844 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2845 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002846 } else {
2847 QualType CanonVecTy = getCanonicalType(vecType);
2848 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002849 New = new (*this, TypeAlignment)
2850 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2851 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002852
2853 DependentSizedExtVectorType *CanonCheck
2854 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2855 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2856 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002857 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2858 } else {
2859 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2860 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002861 New = new (*this, TypeAlignment)
2862 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002863 }
2864 }
Mike Stump11289f42009-09-09 15:08:12 +00002865
Douglas Gregor758a8692009-06-17 21:51:59 +00002866 Types.push_back(New);
2867 return QualType(New, 0);
2868}
2869
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002870/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002871///
Jay Foad39c79802011-01-12 09:06:06 +00002872QualType
2873ASTContext::getFunctionNoProtoType(QualType ResultTy,
2874 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002875 const CallingConv CallConv = Info.getCC();
2876
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002877 // Unique functions, to guarantee there is only one function of a particular
2878 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002879 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002880 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002881
Craig Topper36250ad2014-05-12 05:36:57 +00002882 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002883 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002884 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002885 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002886
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002887 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002888 if (!ResultTy.isCanonical()) {
2889 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002890
Chris Lattner47955de2007-01-27 08:37:20 +00002891 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002892 FunctionNoProtoType *NewIP =
2893 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002894 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002895 }
Mike Stump11289f42009-09-09 15:08:12 +00002896
Roman Divacky65b88cd2011-03-01 17:40:53 +00002897 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002898 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002899 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002900 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002901 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002902 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002903}
2904
Douglas Gregorcd780372013-01-17 23:36:45 +00002905/// \brief Determine whether \p T is canonical as the result type of a function.
2906static bool isCanonicalResultType(QualType T) {
2907 return T.isCanonical() &&
2908 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2909 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2910}
2911
Jay Foad39c79802011-01-12 09:06:06 +00002912QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002913ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002914 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002915 size_t NumArgs = ArgArray.size();
2916
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002917 // Unique functions, to guarantee there is only one function of a particular
2918 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002919 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002920 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2921 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002922
Craig Topper36250ad2014-05-12 05:36:57 +00002923 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002924 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002925 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002926 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002927
2928 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002929 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002930 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002931 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002932 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002933 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002934 isCanonical = false;
2935
2936 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002937 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002938 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002939 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002940 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002941 CanonicalArgs.reserve(NumArgs);
2942 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002943 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002944
John McCalldb40c7f2010-12-14 08:05:40 +00002945 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002946 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002947 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002948
Douglas Gregorcd780372013-01-17 23:36:45 +00002949 // Result types do not have ARC lifetime qualifiers.
2950 QualType CanResultTy = getCanonicalType(ResultTy);
2951 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2952 Qualifiers Qs = CanResultTy.getQualifiers();
2953 Qs.removeObjCLifetime();
2954 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2955 }
2956
Jordan Rose5c382722013-03-08 21:51:21 +00002957 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002958
Chris Lattnerfd4de792007-01-27 01:15:32 +00002959 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002960 FunctionProtoType *NewIP =
2961 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002962 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002963 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002964
John McCall31168b02011-06-15 23:02:42 +00002965 // FunctionProtoType objects are allocated with extra bytes after
2966 // them for three variable size arrays at the end:
2967 // - parameter types
2968 // - exception types
2969 // - consumed-arguments flags
2970 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002971 // expression, or information used to resolve the exception
2972 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002973 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002974 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00002975 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2976 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2977 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002978 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00002979 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002980 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00002981 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002982 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002983 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002984 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002985 Size += NumArgs * sizeof(bool);
2986
John McCalldb40c7f2010-12-14 08:05:40 +00002987 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002988 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002989 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002990 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002991 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002992 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002993}
Chris Lattneref51c202006-11-10 07:17:23 +00002994
John McCalle78aac42010-03-10 03:28:59 +00002995#ifndef NDEBUG
2996static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2997 if (!isa<CXXRecordDecl>(D)) return false;
2998 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2999 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3000 return true;
3001 if (RD->getDescribedClassTemplate() &&
3002 !isa<ClassTemplateSpecializationDecl>(RD))
3003 return true;
3004 return false;
3005}
3006#endif
3007
3008/// getInjectedClassNameType - Return the unique reference to the
3009/// injected class name type for the specified templated declaration.
3010QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003011 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003012 assert(NeedsInjectedClassNameType(Decl));
3013 if (Decl->TypeForDecl) {
3014 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003015 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003016 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3017 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3018 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3019 } else {
John McCall424cec92011-01-19 06:33:43 +00003020 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003021 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003022 Decl->TypeForDecl = newType;
3023 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003024 }
3025 return QualType(Decl->TypeForDecl, 0);
3026}
3027
Douglas Gregor83a586e2008-04-13 21:07:44 +00003028/// getTypeDeclType - Return the unique reference to the type for the
3029/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003030QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003031 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003032 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003033
Richard Smithdda56e42011-04-15 14:24:37 +00003034 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003035 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003036
John McCall96f0b5f2010-03-10 06:48:02 +00003037 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3038 "Template type parameter types are always available.");
3039
John McCall81e38502010-02-16 03:57:14 +00003040 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003041 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003042 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003043 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003044 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003045 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003046 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003047 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003048 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003049 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3050 Decl->TypeForDecl = newType;
3051 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003052 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003053 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003054
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003055 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003056}
3057
Chris Lattner32d920b2007-01-26 02:01:53 +00003058/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003059/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003060QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003061ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3062 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003063 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003064
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003065 if (Canonical.isNull())
3066 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003067 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003068 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003069 Decl->TypeForDecl = newType;
3070 Types.push_back(newType);
3071 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003072}
3073
Jay Foad39c79802011-01-12 09:06:06 +00003074QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003075 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3076
Douglas Gregorec9fd132012-01-14 16:38:05 +00003077 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003078 if (PrevDecl->TypeForDecl)
3079 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3080
John McCall424cec92011-01-19 06:33:43 +00003081 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3082 Decl->TypeForDecl = newType;
3083 Types.push_back(newType);
3084 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003085}
3086
Jay Foad39c79802011-01-12 09:06:06 +00003087QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003088 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3089
Douglas Gregorec9fd132012-01-14 16:38:05 +00003090 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003091 if (PrevDecl->TypeForDecl)
3092 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3093
John McCall424cec92011-01-19 06:33:43 +00003094 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3095 Decl->TypeForDecl = newType;
3096 Types.push_back(newType);
3097 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003098}
3099
John McCall81904512011-01-06 01:58:22 +00003100QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3101 QualType modifiedType,
3102 QualType equivalentType) {
3103 llvm::FoldingSetNodeID id;
3104 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3105
Craig Topper36250ad2014-05-12 05:36:57 +00003106 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003107 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3108 if (type) return QualType(type, 0);
3109
3110 QualType canon = getCanonicalType(equivalentType);
3111 type = new (*this, TypeAlignment)
3112 AttributedType(canon, attrKind, modifiedType, equivalentType);
3113
3114 Types.push_back(type);
3115 AttributedTypes.InsertNode(type, insertPos);
3116
3117 return QualType(type, 0);
3118}
3119
3120
John McCallcebee162009-10-18 09:09:24 +00003121/// \brief Retrieve a substitution-result type.
3122QualType
3123ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003124 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003125 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003126 && "replacement types must always be canonical");
3127
3128 llvm::FoldingSetNodeID ID;
3129 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003130 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003131 SubstTemplateTypeParmType *SubstParm
3132 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3133
3134 if (!SubstParm) {
3135 SubstParm = new (*this, TypeAlignment)
3136 SubstTemplateTypeParmType(Parm, Replacement);
3137 Types.push_back(SubstParm);
3138 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3139 }
3140
3141 return QualType(SubstParm, 0);
3142}
3143
Douglas Gregorada4b792011-01-14 02:55:32 +00003144/// \brief Retrieve a
3145QualType ASTContext::getSubstTemplateTypeParmPackType(
3146 const TemplateTypeParmType *Parm,
3147 const TemplateArgument &ArgPack) {
3148#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003149 for (const auto &P : ArgPack.pack_elements()) {
3150 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3151 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003152 }
3153#endif
3154
3155 llvm::FoldingSetNodeID ID;
3156 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003157 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003158 if (SubstTemplateTypeParmPackType *SubstParm
3159 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3160 return QualType(SubstParm, 0);
3161
3162 QualType Canon;
3163 if (!Parm->isCanonicalUnqualified()) {
3164 Canon = getCanonicalType(QualType(Parm, 0));
3165 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3166 ArgPack);
3167 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3168 }
3169
3170 SubstTemplateTypeParmPackType *SubstParm
3171 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3172 ArgPack);
3173 Types.push_back(SubstParm);
3174 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3175 return QualType(SubstParm, 0);
3176}
3177
Douglas Gregoreff93e02009-02-05 23:33:38 +00003178/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003179/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003180/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003181QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003182 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003183 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003184 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003185 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003186 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003187 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003188 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3189
3190 if (TypeParm)
3191 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003192
Chandler Carruth08836322011-05-01 00:51:33 +00003193 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003194 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003195 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003196
3197 TemplateTypeParmType *TypeCheck
3198 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3199 assert(!TypeCheck && "Template type parameter canonical type broken");
3200 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003201 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003202 TypeParm = new (*this, TypeAlignment)
3203 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003204
3205 Types.push_back(TypeParm);
3206 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3207
3208 return QualType(TypeParm, 0);
3209}
3210
John McCalle78aac42010-03-10 03:28:59 +00003211TypeSourceInfo *
3212ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3213 SourceLocation NameLoc,
3214 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003215 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003216 assert(!Name.getAsDependentTemplateName() &&
3217 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003218 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003219
3220 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003221 TemplateSpecializationTypeLoc TL =
3222 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003223 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003224 TL.setTemplateNameLoc(NameLoc);
3225 TL.setLAngleLoc(Args.getLAngleLoc());
3226 TL.setRAngleLoc(Args.getRAngleLoc());
3227 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3228 TL.setArgLocInfo(i, Args[i].getLocInfo());
3229 return DI;
3230}
3231
Mike Stump11289f42009-09-09 15:08:12 +00003232QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003233ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003234 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003235 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003236 assert(!Template.getAsDependentTemplateName() &&
3237 "No dependent template names here!");
3238
John McCall6b51f282009-11-23 01:53:49 +00003239 unsigned NumArgs = Args.size();
3240
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003241 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003242 ArgVec.reserve(NumArgs);
3243 for (unsigned i = 0; i != NumArgs; ++i)
3244 ArgVec.push_back(Args[i].getArgument());
3245
John McCall2408e322010-04-27 00:57:59 +00003246 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003247 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003248}
3249
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003250#ifndef NDEBUG
3251static bool hasAnyPackExpansions(const TemplateArgument *Args,
3252 unsigned NumArgs) {
3253 for (unsigned I = 0; I != NumArgs; ++I)
3254 if (Args[I].isPackExpansion())
3255 return true;
3256
3257 return true;
3258}
3259#endif
3260
John McCall0ad16662009-10-29 08:12:44 +00003261QualType
3262ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003263 const TemplateArgument *Args,
3264 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003265 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003266 assert(!Template.getAsDependentTemplateName() &&
3267 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003268 // Look through qualified template names.
3269 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3270 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003271
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003272 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003273 Template.getAsTemplateDecl() &&
3274 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003275 QualType CanonType;
3276 if (!Underlying.isNull())
3277 CanonType = getCanonicalType(Underlying);
3278 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003279 // We can get here with an alias template when the specialization contains
3280 // a pack expansion that does not match up with a parameter pack.
3281 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3282 "Caller must compute aliased type");
3283 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003284 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3285 NumArgs);
3286 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003287
Douglas Gregora8e02e72009-07-28 23:00:59 +00003288 // Allocate the (non-canonical) template specialization type, but don't
3289 // try to unique it: these types typically have location information that
3290 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003291 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3292 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003293 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003294 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003295 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003296 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3297 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003298
Douglas Gregor8bf42052009-02-09 18:46:07 +00003299 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003300 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003301}
3302
Mike Stump11289f42009-09-09 15:08:12 +00003303QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003304ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3305 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003306 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003307 assert(!Template.getAsDependentTemplateName() &&
3308 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003309
Douglas Gregore29139c2011-03-03 17:04:51 +00003310 // Look through qualified template names.
3311 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3312 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003313
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003314 // Build the canonical template specialization type.
3315 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003316 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003317 CanonArgs.reserve(NumArgs);
3318 for (unsigned I = 0; I != NumArgs; ++I)
3319 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3320
3321 // Determine whether this canonical template specialization type already
3322 // exists.
3323 llvm::FoldingSetNodeID ID;
3324 TemplateSpecializationType::Profile(ID, CanonTemplate,
3325 CanonArgs.data(), NumArgs, *this);
3326
Craig Topper36250ad2014-05-12 05:36:57 +00003327 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003328 TemplateSpecializationType *Spec
3329 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3330
3331 if (!Spec) {
3332 // Allocate a new canonical template specialization type.
3333 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3334 sizeof(TemplateArgument) * NumArgs),
3335 TypeAlignment);
3336 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3337 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003338 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003339 Types.push_back(Spec);
3340 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3341 }
3342
3343 assert(Spec->isDependentType() &&
3344 "Non-dependent template-id type must have a canonical type");
3345 return QualType(Spec, 0);
3346}
3347
3348QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003349ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3350 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003351 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003352 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003353 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003354
Craig Topper36250ad2014-05-12 05:36:57 +00003355 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003356 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003357 if (T)
3358 return QualType(T, 0);
3359
Douglas Gregorc42075a2010-02-04 18:10:26 +00003360 QualType Canon = NamedType;
3361 if (!Canon.isCanonical()) {
3362 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003363 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3364 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003365 (void)CheckT;
3366 }
3367
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003368 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003369 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003370 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003371 return QualType(T, 0);
3372}
3373
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003374QualType
Jay Foad39c79802011-01-12 09:06:06 +00003375ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003376 llvm::FoldingSetNodeID ID;
3377 ParenType::Profile(ID, InnerType);
3378
Craig Topper36250ad2014-05-12 05:36:57 +00003379 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003380 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3381 if (T)
3382 return QualType(T, 0);
3383
3384 QualType Canon = InnerType;
3385 if (!Canon.isCanonical()) {
3386 Canon = getCanonicalType(InnerType);
3387 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3388 assert(!CheckT && "Paren canonical type broken");
3389 (void)CheckT;
3390 }
3391
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003392 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003393 Types.push_back(T);
3394 ParenTypes.InsertNode(T, InsertPos);
3395 return QualType(T, 0);
3396}
3397
Douglas Gregor02085352010-03-31 20:19:30 +00003398QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3399 NestedNameSpecifier *NNS,
3400 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003401 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003402 if (Canon.isNull()) {
3403 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003404 ElaboratedTypeKeyword CanonKeyword = Keyword;
3405 if (Keyword == ETK_None)
3406 CanonKeyword = ETK_Typename;
3407
3408 if (CanonNNS != NNS || CanonKeyword != Keyword)
3409 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003410 }
3411
3412 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003413 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003414
Craig Topper36250ad2014-05-12 05:36:57 +00003415 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003416 DependentNameType *T
3417 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003418 if (T)
3419 return QualType(T, 0);
3420
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003421 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003422 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003423 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003424 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003425}
3426
Mike Stump11289f42009-09-09 15:08:12 +00003427QualType
John McCallc392f372010-06-11 00:33:02 +00003428ASTContext::getDependentTemplateSpecializationType(
3429 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003430 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003431 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003432 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003433 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003434 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003435 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3436 ArgCopy.push_back(Args[I].getArgument());
3437 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3438 ArgCopy.size(),
3439 ArgCopy.data());
3440}
3441
3442QualType
3443ASTContext::getDependentTemplateSpecializationType(
3444 ElaboratedTypeKeyword Keyword,
3445 NestedNameSpecifier *NNS,
3446 const IdentifierInfo *Name,
3447 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003448 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003449 assert((!NNS || NNS->isDependent()) &&
3450 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003451
Douglas Gregorc42075a2010-02-04 18:10:26 +00003452 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003453 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3454 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003455
Craig Topper36250ad2014-05-12 05:36:57 +00003456 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003457 DependentTemplateSpecializationType *T
3458 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003459 if (T)
3460 return QualType(T, 0);
3461
John McCallc392f372010-06-11 00:33:02 +00003462 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003463
John McCallc392f372010-06-11 00:33:02 +00003464 ElaboratedTypeKeyword CanonKeyword = Keyword;
3465 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3466
3467 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003468 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003469 for (unsigned I = 0; I != NumArgs; ++I) {
3470 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3471 if (!CanonArgs[I].structurallyEquals(Args[I]))
3472 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003473 }
3474
John McCallc392f372010-06-11 00:33:02 +00003475 QualType Canon;
3476 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3477 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3478 Name, NumArgs,
3479 CanonArgs.data());
3480
3481 // Find the insert position again.
3482 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3483 }
3484
3485 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3486 sizeof(TemplateArgument) * NumArgs),
3487 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003488 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003489 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003490 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003491 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003492 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003493}
3494
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003495QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003496 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003497 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003498 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003499
3500 assert(Pattern->containsUnexpandedParameterPack() &&
3501 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003502 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003503 PackExpansionType *T
3504 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3505 if (T)
3506 return QualType(T, 0);
3507
3508 QualType Canon;
3509 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003510 Canon = getCanonicalType(Pattern);
3511 // The canonical type might not contain an unexpanded parameter pack, if it
3512 // contains an alias template specialization which ignores one of its
3513 // parameters.
3514 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003515 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003516
Richard Smith68eea502012-07-16 00:20:35 +00003517 // Find the insert position again, in case we inserted an element into
3518 // PackExpansionTypes and invalidated our insert position.
3519 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3520 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003521 }
3522
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003523 T = new (*this, TypeAlignment)
3524 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003525 Types.push_back(T);
3526 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003527 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003528}
3529
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003530/// CmpProtocolNames - Comparison predicate for sorting protocols
3531/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003532static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3533 ObjCProtocolDecl *const *RHS) {
3534 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003535}
3536
John McCall8b07ec22010-05-15 11:32:37 +00003537static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003538 unsigned NumProtocols) {
3539 if (NumProtocols == 0) return true;
3540
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003541 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3542 return false;
3543
John McCallfc93cf92009-10-22 22:37:11 +00003544 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003545 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003546 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003547 return false;
3548 return true;
3549}
3550
3551static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003552 unsigned &NumProtocols) {
3553 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003554
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003555 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003556 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003557
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003558 // Canonicalize.
3559 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3560 Protocols[I] = Protocols[I]->getCanonicalDecl();
3561
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003562 // Remove duplicates.
3563 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3564 NumProtocols = ProtocolsEnd-Protocols;
3565}
3566
John McCall8b07ec22010-05-15 11:32:37 +00003567QualType ASTContext::getObjCObjectType(QualType BaseType,
3568 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003569 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003570 // If the base type is an interface and there aren't any protocols
3571 // to add, then the interface type will do just fine.
3572 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3573 return BaseType;
3574
3575 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003576 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003577 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003578 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003579 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3580 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003581
John McCall8b07ec22010-05-15 11:32:37 +00003582 // Build the canonical type, which has the canonical base type and
3583 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003584 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003585 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3586 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3587 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003588 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003589 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003590 unsigned UniqueCount = NumProtocols;
3591
John McCallfc93cf92009-10-22 22:37:11 +00003592 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003593 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3594 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003595 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003596 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3597 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003598 }
3599
3600 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003601 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3602 }
3603
3604 unsigned Size = sizeof(ObjCObjectTypeImpl);
3605 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3606 void *Mem = Allocate(Size, TypeAlignment);
3607 ObjCObjectTypeImpl *T =
3608 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3609
3610 Types.push_back(T);
3611 ObjCObjectTypes.InsertNode(T, InsertPos);
3612 return QualType(T, 0);
3613}
3614
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003615/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3616/// protocol list adopt all protocols in QT's qualified-id protocol
3617/// list.
3618bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3619 ObjCInterfaceDecl *IC) {
3620 if (!QT->isObjCQualifiedIdType())
3621 return false;
3622
3623 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3624 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003625 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003626 if (!IC->ClassImplementsProtocol(Proto, false))
3627 return false;
3628 }
3629 return true;
3630 }
3631 return false;
3632}
3633
3634/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3635/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3636/// of protocols.
3637bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3638 ObjCInterfaceDecl *IDecl) {
3639 if (!QT->isObjCQualifiedIdType())
3640 return false;
3641 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3642 if (!OPT)
3643 return false;
3644 if (!IDecl->hasDefinition())
3645 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003646 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3647 CollectInheritedProtocols(IDecl, InheritedProtocols);
3648 if (InheritedProtocols.empty())
3649 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003650 // Check that if every protocol in list of id<plist> conforms to a protcol
3651 // of IDecl's, then bridge casting is ok.
3652 bool Conforms = false;
3653 for (auto *Proto : OPT->quals()) {
3654 Conforms = false;
3655 for (auto *PI : InheritedProtocols) {
3656 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3657 Conforms = true;
3658 break;
3659 }
3660 }
3661 if (!Conforms)
3662 break;
3663 }
3664 if (Conforms)
3665 return true;
3666
Aaron Ballman83731462014-03-17 16:14:00 +00003667 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003668 // If both the right and left sides have qualifiers.
3669 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003670 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003671 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003672 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003673 break;
3674 }
3675 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003676 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003677 }
3678 return true;
3679}
3680
John McCall8b07ec22010-05-15 11:32:37 +00003681/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3682/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003683QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003684 llvm::FoldingSetNodeID ID;
3685 ObjCObjectPointerType::Profile(ID, ObjectT);
3686
Craig Topper36250ad2014-05-12 05:36:57 +00003687 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003688 if (ObjCObjectPointerType *QT =
3689 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3690 return QualType(QT, 0);
3691
3692 // Find the canonical object type.
3693 QualType Canonical;
3694 if (!ObjectT.isCanonical()) {
3695 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3696
3697 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003698 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3699 }
3700
Douglas Gregorf85bee62010-02-08 22:59:26 +00003701 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003702 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3703 ObjCObjectPointerType *QType =
3704 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003705
Steve Narofffb4330f2009-06-17 22:40:22 +00003706 Types.push_back(QType);
3707 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003708 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003709}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003710
Douglas Gregor1c283312010-08-11 12:19:30 +00003711/// getObjCInterfaceType - Return the unique reference to the type for the
3712/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003713QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3714 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003715 if (Decl->TypeForDecl)
3716 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003717
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003718 if (PrevDecl) {
3719 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3720 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3721 return QualType(PrevDecl->TypeForDecl, 0);
3722 }
3723
Douglas Gregor7671e532011-12-16 16:34:57 +00003724 // Prefer the definition, if there is one.
3725 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3726 Decl = Def;
3727
Douglas Gregor1c283312010-08-11 12:19:30 +00003728 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3729 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3730 Decl->TypeForDecl = T;
3731 Types.push_back(T);
3732 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003733}
3734
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003735/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3736/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003737/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003738/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003739/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003740QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003741 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003742 if (tofExpr->isTypeDependent()) {
3743 llvm::FoldingSetNodeID ID;
3744 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003745
Craig Topper36250ad2014-05-12 05:36:57 +00003746 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003747 DependentTypeOfExprType *Canon
3748 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3749 if (Canon) {
3750 // We already have a "canonical" version of an identical, dependent
3751 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003752 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003753 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003754 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003755 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003756 Canon
3757 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003758 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3759 toe = Canon;
3760 }
3761 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003762 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003763 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003764 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003765 Types.push_back(toe);
3766 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003767}
3768
Steve Naroffa773cd52007-08-01 18:02:17 +00003769/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003770/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003771/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003772/// an issue. This doesn't affect the type checker, since it operates
3773/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003774QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003775 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003776 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003777 Types.push_back(tot);
3778 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003779}
3780
Anders Carlssonad6bd352009-06-24 21:24:56 +00003781
Richard Smith8eb1d322014-06-05 20:13:13 +00003782/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3783/// nodes. This would never be helpful, since each such type has its own
3784/// expression, and would not give a significant memory saving, since there
3785/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003786QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003787 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003788
3789 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003790 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003791 // unique dependent type. Two such decltype-specifiers refer to the same
3792 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003793 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003794 llvm::FoldingSetNodeID ID;
3795 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003796
Craig Topper36250ad2014-05-12 05:36:57 +00003797 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003798 DependentDecltypeType *Canon
3799 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003800 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003801 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003802 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003803 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003804 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003805 dt = new (*this, TypeAlignment)
3806 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003807 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003808 dt = new (*this, TypeAlignment)
3809 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003810 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003811 Types.push_back(dt);
3812 return QualType(dt, 0);
3813}
3814
Alexis Hunte852b102011-05-24 22:41:36 +00003815/// getUnaryTransformationType - We don't unique these, since the memory
3816/// savings are minimal and these are rare.
3817QualType ASTContext::getUnaryTransformType(QualType BaseType,
3818 QualType UnderlyingType,
3819 UnaryTransformType::UTTKind Kind)
3820 const {
3821 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003822 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3823 Kind,
3824 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003825 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003826 Types.push_back(Ty);
3827 return QualType(Ty, 0);
3828}
3829
Richard Smith2a7d4812013-05-04 07:00:32 +00003830/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3831/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3832/// canonical deduced-but-dependent 'auto' type.
3833QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003834 bool IsDependent) const {
3835 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003836 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003837
Richard Smith2a7d4812013-05-04 07:00:32 +00003838 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003839 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003840 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003841 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003842 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3843 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003844
Richard Smith74aeef52013-04-26 16:15:35 +00003845 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003846 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003847 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003848 Types.push_back(AT);
3849 if (InsertPos)
3850 AutoTypes.InsertNode(AT, InsertPos);
3851 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003852}
3853
Eli Friedman0dfb8892011-10-06 23:00:33 +00003854/// getAtomicType - Return the uniqued reference to the atomic type for
3855/// the given value type.
3856QualType ASTContext::getAtomicType(QualType T) const {
3857 // Unique pointers, to guarantee there is only one pointer of a particular
3858 // structure.
3859 llvm::FoldingSetNodeID ID;
3860 AtomicType::Profile(ID, T);
3861
Craig Topper36250ad2014-05-12 05:36:57 +00003862 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003863 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3864 return QualType(AT, 0);
3865
3866 // If the atomic value type isn't canonical, this won't be a canonical type
3867 // either, so fill in the canonical type field.
3868 QualType Canonical;
3869 if (!T.isCanonical()) {
3870 Canonical = getAtomicType(getCanonicalType(T));
3871
3872 // Get the new insert position for the node we care about.
3873 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003874 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003875 }
3876 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3877 Types.push_back(New);
3878 AtomicTypes.InsertNode(New, InsertPos);
3879 return QualType(New, 0);
3880}
3881
Richard Smith02e85f32011-04-14 22:09:26 +00003882/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3883QualType ASTContext::getAutoDeductType() const {
3884 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003885 AutoDeductTy = QualType(
3886 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003887 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003888 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003889 return AutoDeductTy;
3890}
3891
3892/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3893QualType ASTContext::getAutoRRefDeductType() const {
3894 if (AutoRRefDeductTy.isNull())
3895 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3896 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3897 return AutoRRefDeductTy;
3898}
3899
Chris Lattnerfb072462007-01-23 05:45:31 +00003900/// getTagDeclType - Return the unique reference to the type for the
3901/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003902QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003903 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003904 // FIXME: What is the design on getTagDeclType when it requires casting
3905 // away const? mutable?
3906 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003907}
3908
Mike Stump11289f42009-09-09 15:08:12 +00003909/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3910/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3911/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003912CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003913 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003914}
Chris Lattnerfb072462007-01-23 05:45:31 +00003915
Hans Wennborg27541db2011-10-27 08:29:09 +00003916/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3917CanQualType ASTContext::getIntMaxType() const {
3918 return getFromTargetType(Target->getIntMaxType());
3919}
3920
3921/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3922CanQualType ASTContext::getUIntMaxType() const {
3923 return getFromTargetType(Target->getUIntMaxType());
3924}
3925
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003926/// getSignedWCharType - Return the type of "signed wchar_t".
3927/// Used when in C++, as a GCC extension.
3928QualType ASTContext::getSignedWCharType() const {
3929 // FIXME: derive from "Target" ?
3930 return WCharTy;
3931}
3932
3933/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3934/// Used when in C++, as a GCC extension.
3935QualType ASTContext::getUnsignedWCharType() const {
3936 // FIXME: derive from "Target" ?
3937 return UnsignedIntTy;
3938}
3939
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003940QualType ASTContext::getIntPtrType() const {
3941 return getFromTargetType(Target->getIntPtrType());
3942}
3943
3944QualType ASTContext::getUIntPtrType() const {
3945 return getCorrespondingUnsignedType(getIntPtrType());
3946}
3947
Hans Wennborg27541db2011-10-27 08:29:09 +00003948/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003949/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3950QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003951 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003952}
3953
Eli Friedman4e91899e2012-11-27 02:58:24 +00003954/// \brief Return the unique type for "pid_t" defined in
3955/// <sys/types.h>. We need this to compute the correct type for vfork().
3956QualType ASTContext::getProcessIDType() const {
3957 return getFromTargetType(Target->getProcessIDType());
3958}
3959
Chris Lattnera21ad802008-04-02 05:18:44 +00003960//===----------------------------------------------------------------------===//
3961// Type Operators
3962//===----------------------------------------------------------------------===//
3963
Jay Foad39c79802011-01-12 09:06:06 +00003964CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003965 // Push qualifiers into arrays, and then discard any remaining
3966 // qualifiers.
3967 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003968 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003969 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003970 QualType Result;
3971 if (isa<ArrayType>(Ty)) {
3972 Result = getArrayDecayedType(QualType(Ty,0));
3973 } else if (isa<FunctionType>(Ty)) {
3974 Result = getPointerType(QualType(Ty, 0));
3975 } else {
3976 Result = QualType(Ty, 0);
3977 }
3978
3979 return CanQualType::CreateUnsafe(Result);
3980}
3981
John McCall6c9dd522011-01-18 07:41:22 +00003982QualType ASTContext::getUnqualifiedArrayType(QualType type,
3983 Qualifiers &quals) {
3984 SplitQualType splitType = type.getSplitUnqualifiedType();
3985
3986 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3987 // the unqualified desugared type and then drops it on the floor.
3988 // We then have to strip that sugar back off with
3989 // getUnqualifiedDesugaredType(), which is silly.
3990 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003991 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003992
3993 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003994 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003995 quals = splitType.Quals;
3996 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003997 }
3998
John McCall6c9dd522011-01-18 07:41:22 +00003999 // Otherwise, recurse on the array's element type.
4000 QualType elementType = AT->getElementType();
4001 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4002
4003 // If that didn't change the element type, AT has no qualifiers, so we
4004 // can just use the results in splitType.
4005 if (elementType == unqualElementType) {
4006 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004007 quals = splitType.Quals;
4008 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004009 }
4010
4011 // Otherwise, add in the qualifiers from the outermost type, then
4012 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004013 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004014
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004015 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004016 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004017 CAT->getSizeModifier(), 0);
4018 }
4019
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004020 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004021 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004022 }
4023
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004024 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004025 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004026 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004027 VAT->getSizeModifier(),
4028 VAT->getIndexTypeCVRQualifiers(),
4029 VAT->getBracketsRange());
4030 }
4031
4032 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004033 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004034 DSAT->getSizeModifier(), 0,
4035 SourceRange());
4036}
4037
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004038/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4039/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4040/// they point to and return true. If T1 and T2 aren't pointer types
4041/// or pointer-to-member types, or if they are not similar at this
4042/// level, returns false and leaves T1 and T2 unchanged. Top-level
4043/// qualifiers on T1 and T2 are ignored. This function will typically
4044/// be called in a loop that successively "unwraps" pointer and
4045/// pointer-to-member types to compare them at each level.
4046bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4047 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4048 *T2PtrType = T2->getAs<PointerType>();
4049 if (T1PtrType && T2PtrType) {
4050 T1 = T1PtrType->getPointeeType();
4051 T2 = T2PtrType->getPointeeType();
4052 return true;
4053 }
4054
4055 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4056 *T2MPType = T2->getAs<MemberPointerType>();
4057 if (T1MPType && T2MPType &&
4058 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4059 QualType(T2MPType->getClass(), 0))) {
4060 T1 = T1MPType->getPointeeType();
4061 T2 = T2MPType->getPointeeType();
4062 return true;
4063 }
4064
David Blaikiebbafb8a2012-03-11 07:00:24 +00004065 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004066 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4067 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4068 if (T1OPType && T2OPType) {
4069 T1 = T1OPType->getPointeeType();
4070 T2 = T2OPType->getPointeeType();
4071 return true;
4072 }
4073 }
4074
4075 // FIXME: Block pointers, too?
4076
4077 return false;
4078}
4079
Jay Foad39c79802011-01-12 09:06:06 +00004080DeclarationNameInfo
4081ASTContext::getNameForTemplate(TemplateName Name,
4082 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004083 switch (Name.getKind()) {
4084 case TemplateName::QualifiedTemplate:
4085 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004086 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004087 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4088 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004089
John McCalld9dfe3a2011-06-30 08:33:18 +00004090 case TemplateName::OverloadedTemplate: {
4091 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4092 // DNInfo work in progress: CHECKME: what about DNLoc?
4093 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4094 }
4095
4096 case TemplateName::DependentTemplate: {
4097 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004098 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004099 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004100 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4101 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004102 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004103 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4104 // DNInfo work in progress: FIXME: source locations?
4105 DeclarationNameLoc DNLoc;
4106 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4107 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4108 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004109 }
4110 }
4111
John McCalld9dfe3a2011-06-30 08:33:18 +00004112 case TemplateName::SubstTemplateTemplateParm: {
4113 SubstTemplateTemplateParmStorage *subst
4114 = Name.getAsSubstTemplateTemplateParm();
4115 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4116 NameLoc);
4117 }
4118
4119 case TemplateName::SubstTemplateTemplateParmPack: {
4120 SubstTemplateTemplateParmPackStorage *subst
4121 = Name.getAsSubstTemplateTemplateParmPack();
4122 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4123 NameLoc);
4124 }
4125 }
4126
4127 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004128}
4129
Jay Foad39c79802011-01-12 09:06:06 +00004130TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004131 switch (Name.getKind()) {
4132 case TemplateName::QualifiedTemplate:
4133 case TemplateName::Template: {
4134 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004135 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004136 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004137 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4138
4139 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004140 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004141 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004142
John McCalld9dfe3a2011-06-30 08:33:18 +00004143 case TemplateName::OverloadedTemplate:
4144 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004145
John McCalld9dfe3a2011-06-30 08:33:18 +00004146 case TemplateName::DependentTemplate: {
4147 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4148 assert(DTN && "Non-dependent template names must refer to template decls.");
4149 return DTN->CanonicalTemplateName;
4150 }
4151
4152 case TemplateName::SubstTemplateTemplateParm: {
4153 SubstTemplateTemplateParmStorage *subst
4154 = Name.getAsSubstTemplateTemplateParm();
4155 return getCanonicalTemplateName(subst->getReplacement());
4156 }
4157
4158 case TemplateName::SubstTemplateTemplateParmPack: {
4159 SubstTemplateTemplateParmPackStorage *subst
4160 = Name.getAsSubstTemplateTemplateParmPack();
4161 TemplateTemplateParmDecl *canonParameter
4162 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4163 TemplateArgument canonArgPack
4164 = getCanonicalTemplateArgument(subst->getArgumentPack());
4165 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4166 }
4167 }
4168
4169 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004170}
4171
Douglas Gregoradee3e32009-11-11 23:06:43 +00004172bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4173 X = getCanonicalTemplateName(X);
4174 Y = getCanonicalTemplateName(Y);
4175 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4176}
4177
Mike Stump11289f42009-09-09 15:08:12 +00004178TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004179ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004180 switch (Arg.getKind()) {
4181 case TemplateArgument::Null:
4182 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004183
Douglas Gregora8e02e72009-07-28 23:00:59 +00004184 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004185 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004186
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004187 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004188 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004189 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004190 }
Mike Stump11289f42009-09-09 15:08:12 +00004191
Eli Friedmanb826a002012-09-26 02:36:12 +00004192 case TemplateArgument::NullPtr:
4193 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4194 /*isNullPtr*/true);
4195
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004196 case TemplateArgument::Template:
4197 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004198
4199 case TemplateArgument::TemplateExpansion:
4200 return TemplateArgument(getCanonicalTemplateName(
4201 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004202 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004203
Douglas Gregora8e02e72009-07-28 23:00:59 +00004204 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004205 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004206
Douglas Gregora8e02e72009-07-28 23:00:59 +00004207 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004208 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004209
Douglas Gregora8e02e72009-07-28 23:00:59 +00004210 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004211 if (Arg.pack_size() == 0)
4212 return Arg;
4213
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004214 TemplateArgument *CanonArgs
4215 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004216 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004217 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004218 AEnd = Arg.pack_end();
4219 A != AEnd; (void)++A, ++Idx)
4220 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004221
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004222 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004223 }
4224 }
4225
4226 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004227 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004228}
4229
Douglas Gregor333489b2009-03-27 23:10:48 +00004230NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004231ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004232 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004233 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004234
4235 switch (NNS->getKind()) {
4236 case NestedNameSpecifier::Identifier:
4237 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004238 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004239 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4240 NNS->getAsIdentifier());
4241
4242 case NestedNameSpecifier::Namespace:
4243 // A namespace is canonical; build a nested-name-specifier with
4244 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004245 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004246 NNS->getAsNamespace()->getOriginalNamespace());
4247
4248 case NestedNameSpecifier::NamespaceAlias:
4249 // A namespace is canonical; build a nested-name-specifier with
4250 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004251 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004252 NNS->getAsNamespaceAlias()->getNamespace()
4253 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004254
4255 case NestedNameSpecifier::TypeSpec:
4256 case NestedNameSpecifier::TypeSpecWithTemplate: {
4257 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004258
4259 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4260 // break it apart into its prefix and identifier, then reconsititute those
4261 // as the canonical nested-name-specifier. This is required to canonicalize
4262 // a dependent nested-name-specifier involving typedefs of dependent-name
4263 // types, e.g.,
4264 // typedef typename T::type T1;
4265 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004266 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4267 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004268 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004269
Eli Friedman5358a0a2012-03-03 04:09:56 +00004270 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4271 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4272 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004273 return NestedNameSpecifier::Create(*this, nullptr, false,
4274 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004275 }
4276
4277 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004278 case NestedNameSpecifier::Super:
4279 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004280 return NNS;
4281 }
4282
David Blaikie8a40f702012-01-17 06:56:22 +00004283 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004284}
4285
Chris Lattner7adf0762008-08-04 07:31:14 +00004286
Jay Foad39c79802011-01-12 09:06:06 +00004287const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004288 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004289 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004290 // Handle the common positive case fast.
4291 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4292 return AT;
4293 }
Mike Stump11289f42009-09-09 15:08:12 +00004294
John McCall8ccfcb52009-09-24 19:53:00 +00004295 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004296 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004297 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004298
John McCall8ccfcb52009-09-24 19:53:00 +00004299 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004300 // implements C99 6.7.3p8: "If the specification of an array type includes
4301 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004302
Chris Lattner7adf0762008-08-04 07:31:14 +00004303 // If we get here, we either have type qualifiers on the type, or we have
4304 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004305 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004306
John McCall33ddac02011-01-19 10:06:00 +00004307 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004308 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004309
Chris Lattner7adf0762008-08-04 07:31:14 +00004310 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004311 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004312 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004313 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004314
Chris Lattner7adf0762008-08-04 07:31:14 +00004315 // Otherwise, we have an array and we have qualifiers on it. Push the
4316 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004317 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004318
Chris Lattner7adf0762008-08-04 07:31:14 +00004319 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4320 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4321 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004322 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004323 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4324 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4325 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004326 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004327
Mike Stump11289f42009-09-09 15:08:12 +00004328 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004329 = dyn_cast<DependentSizedArrayType>(ATy))
4330 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004331 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004332 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004333 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004334 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004335 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004336
Chris Lattner7adf0762008-08-04 07:31:14 +00004337 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004338 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004339 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004340 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004341 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004342 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004343}
4344
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004345QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004346 if (T->isArrayType() || T->isFunctionType())
4347 return getDecayedType(T);
4348 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004349}
4350
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004351QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004352 T = getVariableArrayDecayedType(T);
4353 T = getAdjustedParameterType(T);
4354 return T.getUnqualifiedType();
4355}
4356
David Majnemerd09a51c2015-03-03 01:50:05 +00004357QualType ASTContext::getExceptionObjectType(QualType T) const {
4358 // C++ [except.throw]p3:
4359 // A throw-expression initializes a temporary object, called the exception
4360 // object, the type of which is determined by removing any top-level
4361 // cv-qualifiers from the static type of the operand of throw and adjusting
4362 // the type from "array of T" or "function returning T" to "pointer to T"
4363 // or "pointer to function returning T", [...]
4364 T = getVariableArrayDecayedType(T);
4365 if (T->isArrayType() || T->isFunctionType())
4366 T = getDecayedType(T);
4367 return T.getUnqualifiedType();
4368}
4369
Chris Lattnera21ad802008-04-02 05:18:44 +00004370/// getArrayDecayedType - Return the properly qualified result of decaying the
4371/// specified array type to a pointer. This operation is non-trivial when
4372/// handling typedefs etc. The canonical type of "T" must be an array type,
4373/// this returns a pointer to a properly qualified element of the array.
4374///
4375/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004376QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004377 // Get the element type with 'getAsArrayType' so that we don't lose any
4378 // typedefs in the element type of the array. This also handles propagation
4379 // of type qualifiers from the array type into the element type if present
4380 // (C99 6.7.3p8).
4381 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4382 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004383
Chris Lattner7adf0762008-08-04 07:31:14 +00004384 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004385
4386 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004387 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004388}
4389
John McCall33ddac02011-01-19 10:06:00 +00004390QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4391 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004392}
4393
John McCall33ddac02011-01-19 10:06:00 +00004394QualType ASTContext::getBaseElementType(QualType type) const {
4395 Qualifiers qs;
4396 while (true) {
4397 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004398 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004399 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004400
John McCall33ddac02011-01-19 10:06:00 +00004401 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004402 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004403 }
Mike Stump11289f42009-09-09 15:08:12 +00004404
John McCall33ddac02011-01-19 10:06:00 +00004405 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004406}
4407
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004408/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004409uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004410ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4411 uint64_t ElementCount = 1;
4412 do {
4413 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004414 CA = dyn_cast_or_null<ConstantArrayType>(
4415 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004416 } while (CA);
4417 return ElementCount;
4418}
4419
Steve Naroff0af91202007-04-27 21:51:21 +00004420/// getFloatingRank - Return a relative rank for floating point types.
4421/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004422static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004423 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004424 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004425
John McCall9dd450b2009-09-21 23:43:11 +00004426 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4427 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004428 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004429 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004430 case BuiltinType::Float: return FloatRank;
4431 case BuiltinType::Double: return DoubleRank;
4432 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004433 }
4434}
4435
Mike Stump11289f42009-09-09 15:08:12 +00004436/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4437/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004438/// 'typeDomain' is a real floating point or complex type.
4439/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004440QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4441 QualType Domain) const {
4442 FloatingRank EltRank = getFloatingRank(Size);
4443 if (Domain->isComplexType()) {
4444 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004445 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004446 case FloatRank: return FloatComplexTy;
4447 case DoubleRank: return DoubleComplexTy;
4448 case LongDoubleRank: return LongDoubleComplexTy;
4449 }
Steve Naroff0af91202007-04-27 21:51:21 +00004450 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004451
4452 assert(Domain->isRealFloatingType() && "Unknown domain!");
4453 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004454 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004455 case FloatRank: return FloatTy;
4456 case DoubleRank: return DoubleTy;
4457 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004458 }
David Blaikief47fa302012-01-17 02:30:50 +00004459 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004460}
4461
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004462/// getFloatingTypeOrder - Compare the rank of the two specified floating
4463/// point types, ignoring the domain of the type (i.e. 'double' ==
4464/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004465/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004466int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004467 FloatingRank LHSR = getFloatingRank(LHS);
4468 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004469
Chris Lattnerb90739d2008-04-06 23:38:49 +00004470 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004471 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004472 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004473 return 1;
4474 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004475}
4476
Chris Lattner76a00cf2008-04-06 22:59:24 +00004477/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4478/// routine will assert if passed a built-in type that isn't an integer or enum,
4479/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004480unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004481 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004482
Chris Lattner76a00cf2008-04-06 22:59:24 +00004483 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004484 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004485 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004486 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004487 case BuiltinType::Char_S:
4488 case BuiltinType::Char_U:
4489 case BuiltinType::SChar:
4490 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004491 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004492 case BuiltinType::Short:
4493 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004494 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004495 case BuiltinType::Int:
4496 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004497 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004498 case BuiltinType::Long:
4499 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004500 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004501 case BuiltinType::LongLong:
4502 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004503 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004504 case BuiltinType::Int128:
4505 case BuiltinType::UInt128:
4506 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004507 }
4508}
4509
Eli Friedman629ffb92009-08-20 04:21:42 +00004510/// \brief Whether this is a promotable bitfield reference according
4511/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4512///
4513/// \returns the type this bit-field will promote to, or NULL if no
4514/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004515QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004516 if (E->isTypeDependent() || E->isValueDependent())
4517 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004518
4519 // FIXME: We should not do this unless E->refersToBitField() is true. This
4520 // matters in C where getSourceBitField() will find bit-fields for various
4521 // cases where the source expression is not a bit-field designator.
4522
John McCalld25db7e2013-05-06 21:39:12 +00004523 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004524 if (!Field)
4525 return QualType();
4526
4527 QualType FT = Field->getType();
4528
Richard Smithcaf33902011-10-10 18:28:20 +00004529 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004530 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004531 // C++ [conv.prom]p5:
4532 // A prvalue for an integral bit-field can be converted to a prvalue of type
4533 // int if int can represent all the values of the bit-field; otherwise, it
4534 // can be converted to unsigned int if unsigned int can represent all the
4535 // values of the bit-field. If the bit-field is larger yet, no integral
4536 // promotion applies to it.
4537 // C11 6.3.1.1/2:
4538 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4539 // If an int can represent all values of the original type (as restricted by
4540 // the width, for a bit-field), the value is converted to an int; otherwise,
4541 // it is converted to an unsigned int.
4542 //
4543 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4544 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004545 if (BitWidth < IntSize)
4546 return IntTy;
4547
4548 if (BitWidth == IntSize)
4549 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4550
4551 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004552 // like the base type. GCC has some weird bugs in this area that we
4553 // deliberately do not follow (GCC follows a pre-standard resolution to
4554 // C's DR315 which treats bit-width as being part of the type, and this leaks
4555 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004556 return QualType();
4557}
4558
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004559/// getPromotedIntegerType - Returns the type that Promotable will
4560/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4561/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004562QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004563 assert(!Promotable.isNull());
4564 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004565 if (const EnumType *ET = Promotable->getAs<EnumType>())
4566 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004567
4568 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4569 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4570 // (3.9.1) can be converted to a prvalue of the first of the following
4571 // types that can represent all the values of its underlying type:
4572 // int, unsigned int, long int, unsigned long int, long long int, or
4573 // unsigned long long int [...]
4574 // FIXME: Is there some better way to compute this?
4575 if (BT->getKind() == BuiltinType::WChar_S ||
4576 BT->getKind() == BuiltinType::WChar_U ||
4577 BT->getKind() == BuiltinType::Char16 ||
4578 BT->getKind() == BuiltinType::Char32) {
4579 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4580 uint64_t FromSize = getTypeSize(BT);
4581 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4582 LongLongTy, UnsignedLongLongTy };
4583 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4584 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4585 if (FromSize < ToSize ||
4586 (FromSize == ToSize &&
4587 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4588 return PromoteTypes[Idx];
4589 }
4590 llvm_unreachable("char type should fit into long long");
4591 }
4592 }
4593
4594 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004595 if (Promotable->isSignedIntegerType())
4596 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004597 uint64_t PromotableSize = getIntWidth(Promotable);
4598 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004599 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4600 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4601}
4602
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004603/// \brief Recurses in pointer/array types until it finds an objc retainable
4604/// type and returns its ownership.
4605Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4606 while (!T.isNull()) {
4607 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4608 return T.getObjCLifetime();
4609 if (T->isArrayType())
4610 T = getBaseElementType(T);
4611 else if (const PointerType *PT = T->getAs<PointerType>())
4612 T = PT->getPointeeType();
4613 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004614 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004615 else
4616 break;
4617 }
4618
4619 return Qualifiers::OCL_None;
4620}
4621
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004622static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4623 // Incomplete enum types are not treated as integer types.
4624 // FIXME: In C++, enum types are never integer types.
4625 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4626 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004627 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004628}
4629
Mike Stump11289f42009-09-09 15:08:12 +00004630/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004631/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004632/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004633int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004634 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4635 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004636
4637 // Unwrap enums to their underlying type.
4638 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4639 LHSC = getIntegerTypeForEnum(ET);
4640 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4641 RHSC = getIntegerTypeForEnum(ET);
4642
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004643 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004644
Chris Lattner76a00cf2008-04-06 22:59:24 +00004645 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4646 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004647
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004648 unsigned LHSRank = getIntegerRank(LHSC);
4649 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004650
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004651 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4652 if (LHSRank == RHSRank) return 0;
4653 return LHSRank > RHSRank ? 1 : -1;
4654 }
Mike Stump11289f42009-09-09 15:08:12 +00004655
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004656 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4657 if (LHSUnsigned) {
4658 // If the unsigned [LHS] type is larger, return it.
4659 if (LHSRank >= RHSRank)
4660 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004661
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004662 // If the signed type can represent all values of the unsigned type, it
4663 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004664 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004665 return -1;
4666 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004667
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004668 // If the unsigned [RHS] type is larger, return it.
4669 if (RHSRank >= LHSRank)
4670 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004671
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004672 // If the signed type can represent all values of the unsigned type, it
4673 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004674 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004675 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004676}
Anders Carlsson98f07902007-08-17 05:31:46 +00004677
Mike Stump11289f42009-09-09 15:08:12 +00004678// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004679QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004680 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004681 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004682 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004683
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004684 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004685
Anders Carlsson98f07902007-08-17 05:31:46 +00004686 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004687 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004688 // int flags;
4689 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004690 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004691 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004692 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004693 FieldTypes[3] = LongTy;
4694
Anders Carlsson98f07902007-08-17 05:31:46 +00004695 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004696 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004697 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004698 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004699 SourceLocation(), nullptr,
4700 FieldTypes[i], /*TInfo=*/nullptr,
4701 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004702 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004703 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004704 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004705 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004706 }
4707
Douglas Gregord5058122010-02-11 01:19:42 +00004708 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004709 }
Mike Stump11289f42009-09-09 15:08:12 +00004710
Anders Carlsson98f07902007-08-17 05:31:46 +00004711 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004712}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004713
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004714QualType ASTContext::getObjCSuperType() const {
4715 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004716 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004717 TUDecl->addDecl(ObjCSuperTypeDecl);
4718 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4719 }
4720 return ObjCSuperType;
4721}
4722
Douglas Gregor512b0772009-04-23 22:29:11 +00004723void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004724 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004725 assert(Rec && "Invalid CFConstantStringType");
4726 CFConstantStringTypeDecl = Rec->getDecl();
4727}
4728
Jay Foad39c79802011-01-12 09:06:06 +00004729QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004730 if (BlockDescriptorType)
4731 return getTagDeclType(BlockDescriptorType);
4732
Alp Toker2dea15b2013-12-17 01:22:38 +00004733 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004734 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004735 RD = buildImplicitRecord("__block_descriptor");
4736 RD->startDefinition();
4737
Mike Stumpd0153282009-10-20 02:12:22 +00004738 QualType FieldTypes[] = {
4739 UnsignedLongTy,
4740 UnsignedLongTy,
4741 };
4742
Craig Topperd6d31ac2013-07-15 08:24:27 +00004743 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004744 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004745 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004746 };
4747
4748 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004749 FieldDecl *Field = FieldDecl::Create(
4750 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004751 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4752 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004753 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004754 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004755 }
4756
Alp Toker2dea15b2013-12-17 01:22:38 +00004757 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004758
Alp Toker2dea15b2013-12-17 01:22:38 +00004759 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004760
4761 return getTagDeclType(BlockDescriptorType);
4762}
4763
Jay Foad39c79802011-01-12 09:06:06 +00004764QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004765 if (BlockDescriptorExtendedType)
4766 return getTagDeclType(BlockDescriptorExtendedType);
4767
Alp Toker2dea15b2013-12-17 01:22:38 +00004768 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004769 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004770 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4771 RD->startDefinition();
4772
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004773 QualType FieldTypes[] = {
4774 UnsignedLongTy,
4775 UnsignedLongTy,
4776 getPointerType(VoidPtrTy),
4777 getPointerType(VoidPtrTy)
4778 };
4779
Craig Topperd6d31ac2013-07-15 08:24:27 +00004780 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004781 "reserved",
4782 "Size",
4783 "CopyFuncPtr",
4784 "DestroyFuncPtr"
4785 };
4786
4787 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004788 FieldDecl *Field = FieldDecl::Create(
4789 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004790 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4791 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004792 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004793 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004794 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004795 }
4796
Alp Toker2dea15b2013-12-17 01:22:38 +00004797 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004798
Alp Toker2dea15b2013-12-17 01:22:38 +00004799 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004800 return getTagDeclType(BlockDescriptorExtendedType);
4801}
4802
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004803/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4804/// requires copy/dispose. Note that this must match the logic
4805/// in buildByrefHelpers.
4806bool ASTContext::BlockRequiresCopying(QualType Ty,
4807 const VarDecl *D) {
4808 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4809 const Expr *copyExpr = getBlockVarCopyInits(D);
4810 if (!copyExpr && record->hasTrivialDestructor()) return false;
4811
Mike Stump94967902009-10-21 18:16:27 +00004812 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004813 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004814
4815 if (!Ty->isObjCRetainableType()) return false;
4816
4817 Qualifiers qs = Ty.getQualifiers();
4818
4819 // If we have lifetime, that dominates.
4820 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4821 assert(getLangOpts().ObjCAutoRefCount);
4822
4823 switch (lifetime) {
4824 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4825
4826 // These are just bits as far as the runtime is concerned.
4827 case Qualifiers::OCL_ExplicitNone:
4828 case Qualifiers::OCL_Autoreleasing:
4829 return false;
4830
4831 // Tell the runtime that this is ARC __weak, called by the
4832 // byref routines.
4833 case Qualifiers::OCL_Weak:
4834 // ARC __strong __block variables need to be retained.
4835 case Qualifiers::OCL_Strong:
4836 return true;
4837 }
4838 llvm_unreachable("fell out of lifetime switch!");
4839 }
4840 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4841 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004842}
4843
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004844bool ASTContext::getByrefLifetime(QualType Ty,
4845 Qualifiers::ObjCLifetime &LifeTime,
4846 bool &HasByrefExtendedLayout) const {
4847
4848 if (!getLangOpts().ObjC1 ||
4849 getLangOpts().getGC() != LangOptions::NonGC)
4850 return false;
4851
4852 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004853 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004854 HasByrefExtendedLayout = true;
4855 LifeTime = Qualifiers::OCL_None;
4856 }
4857 else if (getLangOpts().ObjCAutoRefCount)
4858 LifeTime = Ty.getObjCLifetime();
4859 // MRR.
4860 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4861 LifeTime = Qualifiers::OCL_ExplicitNone;
4862 else
4863 LifeTime = Qualifiers::OCL_None;
4864 return true;
4865}
4866
Douglas Gregorbab8a962011-09-08 01:46:34 +00004867TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4868 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004869 ObjCInstanceTypeDecl =
4870 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004871 return ObjCInstanceTypeDecl;
4872}
4873
Anders Carlsson18acd442007-10-29 06:33:42 +00004874// This returns true if a type has been typedefed to BOOL:
4875// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004876static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004877 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004878 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4879 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004880
Anders Carlssond8499822007-10-29 05:01:08 +00004881 return false;
4882}
4883
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004884/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004885/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004886CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004887 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4888 return CharUnits::Zero();
4889
Ken Dyck40775002010-01-11 17:06:35 +00004890 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004891
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004892 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004893 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004894 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004895 // Treat arrays as pointers, since that's how they're passed in.
4896 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004897 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004898 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004899}
4900
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004901bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4902 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4903 VD->getType()->isIntegralOrEnumerationType() &&
4904 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4905}
4906
Ken Dyck40775002010-01-11 17:06:35 +00004907static inline
4908std::string charUnitsToString(const CharUnits &CU) {
4909 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004910}
4911
John McCall351762c2011-02-07 10:33:21 +00004912/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004913/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004914std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4915 std::string S;
4916
David Chisnall950a9512009-11-17 19:33:30 +00004917 const BlockDecl *Decl = Expr->getBlockDecl();
4918 QualType BlockTy =
4919 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4920 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004921 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004922 getObjCEncodingForMethodParameter(
4923 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4924 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004925 else
Alp Toker314cc812014-01-25 16:55:45 +00004926 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004927 // Compute size of all parameters.
4928 // Start with computing size of a pointer in number of bytes.
4929 // FIXME: There might(should) be a better way of doing this computation!
4930 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004931 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4932 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004933 for (auto PI : Decl->params()) {
4934 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004935 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004936 if (sz.isZero())
4937 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004938 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004939 ParmOffset += sz;
4940 }
4941 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004942 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004943 // Block pointer and offset.
4944 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004945
4946 // Argument types.
4947 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004948 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004949 QualType PType = PVDecl->getOriginalType();
4950 if (const ArrayType *AT =
4951 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4952 // Use array's original type only if it has known number of
4953 // elements.
4954 if (!isa<ConstantArrayType>(AT))
4955 PType = PVDecl->getType();
4956 } else if (PType->isFunctionType())
4957 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004958 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004959 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4960 S, true /*Extended*/);
4961 else
4962 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004963 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004964 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004965 }
John McCall351762c2011-02-07 10:33:21 +00004966
4967 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004968}
4969
Douglas Gregora9d84932011-05-27 01:19:52 +00004970bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004971 std::string& S) {
4972 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004973 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004974 CharUnits ParmOffset;
4975 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004976 for (auto PI : Decl->params()) {
4977 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004978 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004979 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004980 continue;
4981
David Chisnall50e4eba2010-12-30 14:05:53 +00004982 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004983 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004984 ParmOffset += sz;
4985 }
4986 S += charUnitsToString(ParmOffset);
4987 ParmOffset = CharUnits::Zero();
4988
4989 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004990 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004991 QualType PType = PVDecl->getOriginalType();
4992 if (const ArrayType *AT =
4993 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4994 // Use array's original type only if it has known number of
4995 // elements.
4996 if (!isa<ConstantArrayType>(AT))
4997 PType = PVDecl->getType();
4998 } else if (PType->isFunctionType())
4999 PType = PVDecl->getType();
5000 getObjCEncodingForType(PType, S);
5001 S += charUnitsToString(ParmOffset);
5002 ParmOffset += getObjCEncodingTypeSize(PType);
5003 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005004
5005 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005006}
5007
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005008/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5009/// method parameter or return type. If Extended, include class names and
5010/// block object types.
5011void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5012 QualType T, std::string& S,
5013 bool Extended) const {
5014 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5015 getObjCEncodingForTypeQualifier(QT, S);
5016 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005017 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005018 true /*OutermostType*/,
5019 false /*EncodingProperty*/,
5020 false /*StructField*/,
5021 Extended /*EncodeBlockParameters*/,
5022 Extended /*EncodeClassNames*/);
5023}
5024
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005025/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005026/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005027bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005028 std::string& S,
5029 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005030 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005031 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005032 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5033 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005034 // Compute size of all parameters.
5035 // Start with computing size of a pointer in number of bytes.
5036 // FIXME: There might(should) be a better way of doing this computation!
5037 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005038 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005039 // The first two arguments (self and _cmd) are pointers; account for
5040 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005041 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005042 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005043 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005044 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005045 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005046 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005047 continue;
5048
Ken Dyck40775002010-01-11 17:06:35 +00005049 assert (sz.isPositive() &&
5050 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005051 ParmOffset += sz;
5052 }
Ken Dyck40775002010-01-11 17:06:35 +00005053 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005054 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005055 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005056
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005057 // Argument types.
5058 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005059 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005060 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005061 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005062 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005063 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005064 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5065 // Use array's original type only if it has known number of
5066 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005067 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005068 PType = PVDecl->getType();
5069 } else if (PType->isFunctionType())
5070 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005071 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5072 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005073 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005074 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005075 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005076
5077 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005078}
5079
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005080ObjCPropertyImplDecl *
5081ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5082 const ObjCPropertyDecl *PD,
5083 const Decl *Container) const {
5084 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005085 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005086 if (const ObjCCategoryImplDecl *CID =
5087 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005088 for (auto *PID : CID->property_impls())
5089 if (PID->getPropertyDecl() == PD)
5090 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005091 } else {
5092 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5093 for (auto *PID : OID->property_impls())
5094 if (PID->getPropertyDecl() == PD)
5095 return PID;
5096 }
5097 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005098}
5099
Daniel Dunbar4932b362008-08-28 04:38:10 +00005100/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005101/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005102/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5103/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005104/// Property attributes are stored as a comma-delimited C string. The simple
5105/// attributes readonly and bycopy are encoded as single characters. The
5106/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5107/// encoded as single characters, followed by an identifier. Property types
5108/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005109/// these attributes are defined by the following enumeration:
5110/// @code
5111/// enum PropertyAttributes {
5112/// kPropertyReadOnly = 'R', // property is read-only.
5113/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5114/// kPropertyByref = '&', // property is a reference to the value last assigned
5115/// kPropertyDynamic = 'D', // property is dynamic
5116/// kPropertyGetter = 'G', // followed by getter selector name
5117/// kPropertySetter = 'S', // followed by setter selector name
5118/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005119/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005120/// kPropertyWeak = 'W' // 'weak' property
5121/// kPropertyStrong = 'P' // property GC'able
5122/// kPropertyNonAtomic = 'N' // property non-atomic
5123/// };
5124/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005125void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005126 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005127 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005128 // Collect information from the property implementation decl(s).
5129 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005130 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005131
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005132 if (ObjCPropertyImplDecl *PropertyImpDecl =
5133 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5134 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5135 Dynamic = true;
5136 else
5137 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005138 }
5139
5140 // FIXME: This is not very efficient.
5141 S = "T";
5142
5143 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005144 // GCC has some special rules regarding encoding of properties which
5145 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005146 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005147
5148 if (PD->isReadOnly()) {
5149 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005150 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5151 S += ",C";
5152 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5153 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005154 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5155 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005156 } else {
5157 switch (PD->getSetterKind()) {
5158 case ObjCPropertyDecl::Assign: break;
5159 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005160 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005161 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005162 }
5163 }
5164
5165 // It really isn't clear at all what this means, since properties
5166 // are "dynamic by default".
5167 if (Dynamic)
5168 S += ",D";
5169
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005170 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5171 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005172
Daniel Dunbar4932b362008-08-28 04:38:10 +00005173 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5174 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005175 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005176 }
5177
5178 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5179 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005180 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005181 }
5182
5183 if (SynthesizePID) {
5184 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5185 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005186 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005187 }
5188
5189 // FIXME: OBJCGC: weak & strong
5190}
5191
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005192/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005193/// Another legacy compatibility encoding: 32-bit longs are encoded as
5194/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005195/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5196///
5197void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005198 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005199 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005200 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005201 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005202 else
Jay Foad39c79802011-01-12 09:06:06 +00005203 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005204 PointeeTy = IntTy;
5205 }
5206 }
5207}
5208
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005209void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005210 const FieldDecl *Field,
5211 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005212 // We follow the behavior of gcc, expanding structures which are
5213 // directly pointed to, and expanding embedded structures. Note that
5214 // these rules are sufficient to prevent recursive encoding of the
5215 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005216 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005217 true /* outermost type */, false, false,
5218 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005219}
5220
Joe Groff98ac7d22014-07-07 22:25:15 +00005221void ASTContext::getObjCEncodingForPropertyType(QualType T,
5222 std::string& S) const {
5223 // Encode result type.
5224 // GCC has some special rules regarding encoding of properties which
5225 // closely resembles encoding of ivars.
5226 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5227 true /* outermost type */,
5228 true /* encoding property */);
5229}
5230
John McCall393a78d2012-12-20 02:45:14 +00005231static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5232 BuiltinType::Kind kind) {
5233 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005234 case BuiltinType::Void: return 'v';
5235 case BuiltinType::Bool: return 'B';
5236 case BuiltinType::Char_U:
5237 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005238 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005239 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005240 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005241 case BuiltinType::UInt: return 'I';
5242 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005243 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005244 case BuiltinType::UInt128: return 'T';
5245 case BuiltinType::ULongLong: return 'Q';
5246 case BuiltinType::Char_S:
5247 case BuiltinType::SChar: return 'c';
5248 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005249 case BuiltinType::WChar_S:
5250 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005251 case BuiltinType::Int: return 'i';
5252 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005253 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005254 case BuiltinType::LongLong: return 'q';
5255 case BuiltinType::Int128: return 't';
5256 case BuiltinType::Float: return 'f';
5257 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005258 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005259 case BuiltinType::NullPtr: return '*'; // like char*
5260
5261 case BuiltinType::Half:
5262 // FIXME: potentially need @encodes for these!
5263 return ' ';
5264
5265 case BuiltinType::ObjCId:
5266 case BuiltinType::ObjCClass:
5267 case BuiltinType::ObjCSel:
5268 llvm_unreachable("@encoding ObjC primitive type");
5269
5270 // OpenCL and placeholder types don't need @encodings.
5271 case BuiltinType::OCLImage1d:
5272 case BuiltinType::OCLImage1dArray:
5273 case BuiltinType::OCLImage1dBuffer:
5274 case BuiltinType::OCLImage2d:
5275 case BuiltinType::OCLImage2dArray:
5276 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005277 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005278 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005279 case BuiltinType::Dependent:
5280#define BUILTIN_TYPE(KIND, ID)
5281#define PLACEHOLDER_TYPE(KIND, ID) \
5282 case BuiltinType::KIND:
5283#include "clang/AST/BuiltinTypes.def"
5284 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005285 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005286 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005287}
5288
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005289static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5290 EnumDecl *Enum = ET->getDecl();
5291
5292 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5293 if (!Enum->isFixed())
5294 return 'i';
5295
5296 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005297 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5298 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005299}
5300
Jay Foad39c79802011-01-12 09:06:06 +00005301static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005302 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005303 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005304 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005305 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5306 // The GNU runtime requires more information; bitfields are encoded as b,
5307 // then the offset (in bits) of the first element, then the type of the
5308 // bitfield, then the size in bits. For example, in this structure:
5309 //
5310 // struct
5311 // {
5312 // int integer;
5313 // int flags:2;
5314 // };
5315 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5316 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5317 // information is not especially sensible, but we're stuck with it for
5318 // compatibility with GCC, although providing it breaks anything that
5319 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005320 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005321 const RecordDecl *RD = FD->getParent();
5322 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005323 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005324 if (const EnumType *ET = T->getAs<EnumType>())
5325 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005326 else {
5327 const BuiltinType *BT = T->castAs<BuiltinType>();
5328 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5329 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005330 }
Richard Smithcaf33902011-10-10 18:28:20 +00005331 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005332}
5333
Daniel Dunbar07d07852009-10-18 21:17:35 +00005334// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005335void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5336 bool ExpandPointedToStructures,
5337 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005338 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005339 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005340 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005341 bool StructField,
5342 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005343 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005344 bool EncodePointerToObjCTypedef,
5345 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005346 CanQualType CT = getCanonicalType(T);
5347 switch (CT->getTypeClass()) {
5348 case Type::Builtin:
5349 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005350 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005351 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005352 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5353 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5354 else
5355 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005356 return;
Mike Stump11289f42009-09-09 15:08:12 +00005357
John McCall393a78d2012-12-20 02:45:14 +00005358 case Type::Complex: {
5359 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005360 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005361 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005362 return;
5363 }
John McCall393a78d2012-12-20 02:45:14 +00005364
5365 case Type::Atomic: {
5366 const AtomicType *AT = T->castAs<AtomicType>();
5367 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005368 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005369 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005370 }
John McCall393a78d2012-12-20 02:45:14 +00005371
5372 // encoding for pointer or reference types.
5373 case Type::Pointer:
5374 case Type::LValueReference:
5375 case Type::RValueReference: {
5376 QualType PointeeTy;
5377 if (isa<PointerType>(CT)) {
5378 const PointerType *PT = T->castAs<PointerType>();
5379 if (PT->isObjCSelType()) {
5380 S += ':';
5381 return;
5382 }
5383 PointeeTy = PT->getPointeeType();
5384 } else {
5385 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5386 }
5387
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005388 bool isReadOnly = false;
5389 // For historical/compatibility reasons, the read-only qualifier of the
5390 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5391 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005392 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005393 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005394 if (OutermostType && T.isConstQualified()) {
5395 isReadOnly = true;
5396 S += 'r';
5397 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005398 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005399 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005400 while (P->getAs<PointerType>())
5401 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005402 if (P.isConstQualified()) {
5403 isReadOnly = true;
5404 S += 'r';
5405 }
5406 }
5407 if (isReadOnly) {
5408 // Another legacy compatibility encoding. Some ObjC qualifier and type
5409 // combinations need to be rearranged.
5410 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005411 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005412 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005413 }
Mike Stump11289f42009-09-09 15:08:12 +00005414
Anders Carlssond8499822007-10-29 05:01:08 +00005415 if (PointeeTy->isCharType()) {
5416 // char pointer types should be encoded as '*' unless it is a
5417 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005418 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005419 S += '*';
5420 return;
5421 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005422 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005423 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5424 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5425 S += '#';
5426 return;
5427 }
5428 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5429 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5430 S += '@';
5431 return;
5432 }
5433 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005434 }
Anders Carlssond8499822007-10-29 05:01:08 +00005435 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005436 getLegacyIntegralTypeEncoding(PointeeTy);
5437
Mike Stump11289f42009-09-09 15:08:12 +00005438 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005439 nullptr, false, false, false, false, false, false,
5440 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005441 return;
5442 }
John McCall393a78d2012-12-20 02:45:14 +00005443
5444 case Type::ConstantArray:
5445 case Type::IncompleteArray:
5446 case Type::VariableArray: {
5447 const ArrayType *AT = cast<ArrayType>(CT);
5448
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005449 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005450 // Incomplete arrays are encoded as a pointer to the array element.
5451 S += '^';
5452
Mike Stump11289f42009-09-09 15:08:12 +00005453 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005454 false, ExpandStructures, FD);
5455 } else {
5456 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005457
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005458 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5459 S += llvm::utostr(CAT->getSize().getZExtValue());
5460 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005461 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005462 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5463 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005464 S += '0';
5465 }
Mike Stump11289f42009-09-09 15:08:12 +00005466
5467 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005468 false, ExpandStructures, FD,
5469 false, false, false, false, false, false,
5470 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005471 S += ']';
5472 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005473 return;
5474 }
Mike Stump11289f42009-09-09 15:08:12 +00005475
John McCall393a78d2012-12-20 02:45:14 +00005476 case Type::FunctionNoProto:
5477 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005478 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005479 return;
Mike Stump11289f42009-09-09 15:08:12 +00005480
John McCall393a78d2012-12-20 02:45:14 +00005481 case Type::Record: {
5482 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005483 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005484 // Anonymous structures print as '?'
5485 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5486 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005487 if (ClassTemplateSpecializationDecl *Spec
5488 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5489 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005490 llvm::raw_string_ostream OS(S);
5491 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005492 TemplateArgs.data(),
5493 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005494 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005495 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005496 } else {
5497 S += '?';
5498 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005499 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005500 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005501 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005502 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005503 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005504 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005505 if (FD) {
5506 S += '"';
5507 S += Field->getNameAsString();
5508 S += '"';
5509 }
Mike Stump11289f42009-09-09 15:08:12 +00005510
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005511 // Special case bit-fields.
5512 if (Field->isBitField()) {
5513 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005514 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005515 } else {
5516 QualType qt = Field->getType();
5517 getLegacyIntegralTypeEncoding(qt);
5518 getObjCEncodingForTypeImpl(qt, S, false, true,
5519 FD, /*OutermostType*/false,
5520 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005521 /*StructField*/true,
5522 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005523 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005524 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005525 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005526 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005527 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005528 return;
5529 }
Mike Stump11289f42009-09-09 15:08:12 +00005530
John McCall393a78d2012-12-20 02:45:14 +00005531 case Type::BlockPointer: {
5532 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005533 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005534 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005535 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005536
5537 S += '<';
5538 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005539 getObjCEncodingForTypeImpl(
5540 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5541 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005542 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5543 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005544 // Block self
5545 S += "@?";
5546 // Block parameters
5547 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005548 for (const auto &I : FPT->param_types())
5549 getObjCEncodingForTypeImpl(
5550 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5551 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005552 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5553 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005554 }
5555 S += '>';
5556 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005557 return;
5558 }
Mike Stump11289f42009-09-09 15:08:12 +00005559
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005560 case Type::ObjCObject: {
5561 // hack to match legacy encoding of *id and *Class
5562 QualType Ty = getObjCObjectPointerType(CT);
5563 if (Ty->isObjCIdType()) {
5564 S += "{objc_object=}";
5565 return;
5566 }
5567 else if (Ty->isObjCClassType()) {
5568 S += "{objc_class=}";
5569 return;
5570 }
5571 }
5572
John McCall393a78d2012-12-20 02:45:14 +00005573 case Type::ObjCInterface: {
5574 // Ignore protocol qualifiers when mangling at this level.
5575 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005576
John McCall393a78d2012-12-20 02:45:14 +00005577 // The assumption seems to be that this assert will succeed
5578 // because nested levels will have filtered out 'id' and 'Class'.
5579 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005580 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005581 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005582 S += '{';
5583 const IdentifierInfo *II = OI->getIdentifier();
5584 S += II->getName();
5585 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005586 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005587 DeepCollectObjCIvars(OI, true, Ivars);
5588 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005589 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005590 if (Field->isBitField())
5591 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005592 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005593 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5594 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005595 EncodePointerToObjCTypedef,
5596 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005597 }
5598 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005599 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005600 }
Mike Stump11289f42009-09-09 15:08:12 +00005601
John McCall393a78d2012-12-20 02:45:14 +00005602 case Type::ObjCObjectPointer: {
5603 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005604 if (OPT->isObjCIdType()) {
5605 S += '@';
5606 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005607 }
Mike Stump11289f42009-09-09 15:08:12 +00005608
Steve Narofff0c86112009-10-28 22:03:49 +00005609 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5610 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5611 // Since this is a binary compatibility issue, need to consult with runtime
5612 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005613 S += '#';
5614 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005615 }
Mike Stump11289f42009-09-09 15:08:12 +00005616
Chris Lattnere7cabb92009-07-13 00:10:46 +00005617 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005618 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005619 ExpandPointedToStructures,
5620 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005621 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005622 // Note that we do extended encoding of protocol qualifer list
5623 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005624 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005625 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005626 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005627 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005628 S += '>';
5629 }
5630 S += '"';
5631 }
5632 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005633 }
Mike Stump11289f42009-09-09 15:08:12 +00005634
Chris Lattnere7cabb92009-07-13 00:10:46 +00005635 QualType PointeeTy = OPT->getPointeeType();
5636 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005637 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5638 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005639 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005640 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005641 // {...};
5642 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005643 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005644 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005645 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5646 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5647 DeepCollectObjCIvars(OI, true, Ivars);
5648 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5649 if (cast<FieldDecl>(Ivars[i]) == FD) {
5650 S += '{';
5651 S += OI->getIdentifier()->getName();
5652 S += '}';
5653 return;
5654 }
5655 }
5656 }
Mike Stump11289f42009-09-09 15:08:12 +00005657 getObjCEncodingForTypeImpl(PointeeTy, S,
5658 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005659 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005660 false, false, false, false, false,
5661 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005662 return;
5663 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005664
5665 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005666 if (OPT->getInterfaceDecl() &&
5667 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005668 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005669 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005670 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005671 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005672 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005673 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005674 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005675 S += '"';
5676 }
5677 return;
5678 }
Mike Stump11289f42009-09-09 15:08:12 +00005679
John McCalla9e6e8d2010-05-17 23:56:34 +00005680 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005681 // FIXME: we shoul do better than that. 'M' is available.
5682 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005683 // This matches gcc's encoding, even though technically it is insufficient.
5684 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005685 case Type::Vector:
5686 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005687 // Until we have a coherent encoding of these three types, issue warning.
5688 { if (NotEncodedT)
5689 *NotEncodedT = T;
5690 return;
5691 }
5692
5693 // We could see an undeduced auto type here during error recovery.
5694 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005695 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005696 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005697
Richard Smith27d807c2013-04-30 13:56:41 +00005698
John McCall393a78d2012-12-20 02:45:14 +00005699#define ABSTRACT_TYPE(KIND, BASE)
5700#define TYPE(KIND, BASE)
5701#define DEPENDENT_TYPE(KIND, BASE) \
5702 case Type::KIND:
5703#define NON_CANONICAL_TYPE(KIND, BASE) \
5704 case Type::KIND:
5705#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5706 case Type::KIND:
5707#include "clang/AST/TypeNodes.def"
5708 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005709 }
John McCall393a78d2012-12-20 02:45:14 +00005710 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005711}
5712
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005713void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5714 std::string &S,
5715 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005716 bool includeVBases,
5717 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005718 assert(RDecl && "Expected non-null RecordDecl");
5719 assert(!RDecl->isUnion() && "Should not be called for unions");
5720 if (!RDecl->getDefinition())
5721 return;
5722
5723 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5724 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5725 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5726
5727 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005728 for (const auto &BI : CXXRec->bases()) {
5729 if (!BI.isVirtual()) {
5730 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005731 if (base->isEmpty())
5732 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005733 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005734 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5735 std::make_pair(offs, base));
5736 }
5737 }
5738 }
5739
5740 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005741 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005742 uint64_t offs = layout.getFieldOffset(i);
5743 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005744 std::make_pair(offs, Field));
5745 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005746 }
5747
5748 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005749 for (const auto &BI : CXXRec->vbases()) {
5750 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005751 if (base->isEmpty())
5752 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005753 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005754 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5755 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005756 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5757 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005758 }
5759 }
5760
5761 CharUnits size;
5762 if (CXXRec) {
5763 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5764 } else {
5765 size = layout.getSize();
5766 }
5767
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005768#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005769 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005770#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005771 std::multimap<uint64_t, NamedDecl *>::iterator
5772 CurLayObj = FieldOrBaseOffsets.begin();
5773
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005774 if (CXXRec && CXXRec->isDynamicClass() &&
5775 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005776 if (FD) {
5777 S += "\"_vptr$";
5778 std::string recname = CXXRec->getNameAsString();
5779 if (recname.empty()) recname = "?";
5780 S += recname;
5781 S += '"';
5782 }
5783 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005784#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005785 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005786#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005787 }
5788
5789 if (!RDecl->hasFlexibleArrayMember()) {
5790 // Mark the end of the structure.
5791 uint64_t offs = toBits(size);
5792 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005793 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005794 }
5795
5796 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005797#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005798 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005799 if (CurOffs < CurLayObj->first) {
5800 uint64_t padding = CurLayObj->first - CurOffs;
5801 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5802 // packing/alignment of members is different that normal, in which case
5803 // the encoding will be out-of-sync with the real layout.
5804 // If the runtime switches to just consider the size of types without
5805 // taking into account alignment, we could make padding explicit in the
5806 // encoding (e.g. using arrays of chars). The encoding strings would be
5807 // longer then though.
5808 CurOffs += padding;
5809 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005810#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005811
5812 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005813 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005814 break; // reached end of structure.
5815
5816 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5817 // We expand the bases without their virtual bases since those are going
5818 // in the initial structure. Note that this differs from gcc which
5819 // expands virtual bases each time one is encountered in the hierarchy,
5820 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005821 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5822 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005823 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005824#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005825 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005826#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005827 } else {
5828 FieldDecl *field = cast<FieldDecl>(dcl);
5829 if (FD) {
5830 S += '"';
5831 S += field->getNameAsString();
5832 S += '"';
5833 }
5834
5835 if (field->isBitField()) {
5836 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005837#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005838 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005839#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005840 } else {
5841 QualType qt = field->getType();
5842 getLegacyIntegralTypeEncoding(qt);
5843 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5844 /*OutermostType*/false,
5845 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005846 /*StructField*/true,
5847 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005848#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005849 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005850#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005851 }
5852 }
5853 }
5854}
5855
Mike Stump11289f42009-09-09 15:08:12 +00005856void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005857 std::string& S) const {
5858 if (QT & Decl::OBJC_TQ_In)
5859 S += 'n';
5860 if (QT & Decl::OBJC_TQ_Inout)
5861 S += 'N';
5862 if (QT & Decl::OBJC_TQ_Out)
5863 S += 'o';
5864 if (QT & Decl::OBJC_TQ_Bycopy)
5865 S += 'O';
5866 if (QT & Decl::OBJC_TQ_Byref)
5867 S += 'R';
5868 if (QT & Decl::OBJC_TQ_Oneway)
5869 S += 'V';
5870}
5871
Douglas Gregor3ea72692011-08-12 05:46:01 +00005872TypedefDecl *ASTContext::getObjCIdDecl() const {
5873 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005874 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005875 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005876 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005877 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005878 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005879}
5880
Douglas Gregor52e02802011-08-12 06:17:30 +00005881TypedefDecl *ASTContext::getObjCSelDecl() const {
5882 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005883 QualType T = getPointerType(ObjCBuiltinSelTy);
5884 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005885 }
5886 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005887}
5888
Douglas Gregor0a586182011-08-12 05:59:41 +00005889TypedefDecl *ASTContext::getObjCClassDecl() const {
5890 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005891 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005892 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005893 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005894 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005895 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005896}
5897
Douglas Gregord53ae832012-01-17 18:09:05 +00005898ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5899 if (!ObjCProtocolClassDecl) {
5900 ObjCProtocolClassDecl
5901 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5902 SourceLocation(),
5903 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005904 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005905 SourceLocation(), true);
5906 }
5907
5908 return ObjCProtocolClassDecl;
5909}
5910
Meador Inge5d3fb222012-06-16 03:34:49 +00005911//===----------------------------------------------------------------------===//
5912// __builtin_va_list Construction Functions
5913//===----------------------------------------------------------------------===//
5914
5915static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5916 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005917 QualType T = Context->getPointerType(Context->CharTy);
5918 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005919}
5920
5921static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5922 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005923 QualType T = Context->getPointerType(Context->VoidTy);
5924 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005925}
5926
Tim Northover9bb857a2013-01-31 12:13:10 +00005927static TypedefDecl *
5928CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005929 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005930 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005931 if (Context->getLangOpts().CPlusPlus) {
5932 // namespace std { struct __va_list {
5933 NamespaceDecl *NS;
5934 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5935 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005936 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005937 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005938 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005939 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005940 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005941 }
5942
5943 VaListTagDecl->startDefinition();
5944
5945 const size_t NumFields = 5;
5946 QualType FieldTypes[NumFields];
5947 const char *FieldNames[NumFields];
5948
5949 // void *__stack;
5950 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5951 FieldNames[0] = "__stack";
5952
5953 // void *__gr_top;
5954 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5955 FieldNames[1] = "__gr_top";
5956
5957 // void *__vr_top;
5958 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5959 FieldNames[2] = "__vr_top";
5960
5961 // int __gr_offs;
5962 FieldTypes[3] = Context->IntTy;
5963 FieldNames[3] = "__gr_offs";
5964
5965 // int __vr_offs;
5966 FieldTypes[4] = Context->IntTy;
5967 FieldNames[4] = "__vr_offs";
5968
5969 // Create fields
5970 for (unsigned i = 0; i < NumFields; ++i) {
5971 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5972 VaListTagDecl,
5973 SourceLocation(),
5974 SourceLocation(),
5975 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005976 FieldTypes[i], /*TInfo=*/nullptr,
5977 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005978 /*Mutable=*/false,
5979 ICIS_NoInit);
5980 Field->setAccess(AS_public);
5981 VaListTagDecl->addDecl(Field);
5982 }
5983 VaListTagDecl->completeDefinition();
5984 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5985 Context->VaListTagTy = VaListTagType;
5986
5987 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005988 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005989}
5990
Meador Inge5d3fb222012-06-16 03:34:49 +00005991static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5992 // typedef struct __va_list_tag {
5993 RecordDecl *VaListTagDecl;
5994
Alp Toker2dea15b2013-12-17 01:22:38 +00005995 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005996 VaListTagDecl->startDefinition();
5997
5998 const size_t NumFields = 5;
5999 QualType FieldTypes[NumFields];
6000 const char *FieldNames[NumFields];
6001
6002 // unsigned char gpr;
6003 FieldTypes[0] = Context->UnsignedCharTy;
6004 FieldNames[0] = "gpr";
6005
6006 // unsigned char fpr;
6007 FieldTypes[1] = Context->UnsignedCharTy;
6008 FieldNames[1] = "fpr";
6009
6010 // unsigned short reserved;
6011 FieldTypes[2] = Context->UnsignedShortTy;
6012 FieldNames[2] = "reserved";
6013
6014 // void* overflow_arg_area;
6015 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6016 FieldNames[3] = "overflow_arg_area";
6017
6018 // void* reg_save_area;
6019 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6020 FieldNames[4] = "reg_save_area";
6021
6022 // Create fields
6023 for (unsigned i = 0; i < NumFields; ++i) {
6024 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6025 SourceLocation(),
6026 SourceLocation(),
6027 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006028 FieldTypes[i], /*TInfo=*/nullptr,
6029 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006030 /*Mutable=*/false,
6031 ICIS_NoInit);
6032 Field->setAccess(AS_public);
6033 VaListTagDecl->addDecl(Field);
6034 }
6035 VaListTagDecl->completeDefinition();
6036 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006037 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006038
6039 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006040 TypedefDecl *VaListTagTypedefDecl =
6041 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6042
Meador Inge5d3fb222012-06-16 03:34:49 +00006043 QualType VaListTagTypedefType =
6044 Context->getTypedefType(VaListTagTypedefDecl);
6045
6046 // typedef __va_list_tag __builtin_va_list[1];
6047 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6048 QualType VaListTagArrayType
6049 = Context->getConstantArrayType(VaListTagTypedefType,
6050 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006051 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006052}
6053
6054static TypedefDecl *
6055CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6056 // typedef struct __va_list_tag {
6057 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006058 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006059 VaListTagDecl->startDefinition();
6060
6061 const size_t NumFields = 4;
6062 QualType FieldTypes[NumFields];
6063 const char *FieldNames[NumFields];
6064
6065 // unsigned gp_offset;
6066 FieldTypes[0] = Context->UnsignedIntTy;
6067 FieldNames[0] = "gp_offset";
6068
6069 // unsigned fp_offset;
6070 FieldTypes[1] = Context->UnsignedIntTy;
6071 FieldNames[1] = "fp_offset";
6072
6073 // void* overflow_arg_area;
6074 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6075 FieldNames[2] = "overflow_arg_area";
6076
6077 // void* reg_save_area;
6078 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6079 FieldNames[3] = "reg_save_area";
6080
6081 // Create fields
6082 for (unsigned i = 0; i < NumFields; ++i) {
6083 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6084 VaListTagDecl,
6085 SourceLocation(),
6086 SourceLocation(),
6087 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006088 FieldTypes[i], /*TInfo=*/nullptr,
6089 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006090 /*Mutable=*/false,
6091 ICIS_NoInit);
6092 Field->setAccess(AS_public);
6093 VaListTagDecl->addDecl(Field);
6094 }
6095 VaListTagDecl->completeDefinition();
6096 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006097 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006098
6099 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006100 TypedefDecl *VaListTagTypedefDecl =
6101 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6102
Meador Inge5d3fb222012-06-16 03:34:49 +00006103 QualType VaListTagTypedefType =
6104 Context->getTypedefType(VaListTagTypedefDecl);
6105
6106 // typedef __va_list_tag __builtin_va_list[1];
6107 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6108 QualType VaListTagArrayType
6109 = Context->getConstantArrayType(VaListTagTypedefType,
6110 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006111 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006112}
6113
6114static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6115 // typedef int __builtin_va_list[4];
6116 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6117 QualType IntArrayType
6118 = Context->getConstantArrayType(Context->IntTy,
6119 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006120 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006121}
6122
Logan Chien57086ce2012-10-10 06:56:20 +00006123static TypedefDecl *
6124CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006125 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006126 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006127 if (Context->getLangOpts().CPlusPlus) {
6128 // namespace std { struct __va_list {
6129 NamespaceDecl *NS;
6130 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6131 Context->getTranslationUnitDecl(),
6132 /*Inline*/false, SourceLocation(),
6133 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006134 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006135 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006136 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006137 }
6138
6139 VaListDecl->startDefinition();
6140
6141 // void * __ap;
6142 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6143 VaListDecl,
6144 SourceLocation(),
6145 SourceLocation(),
6146 &Context->Idents.get("__ap"),
6147 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006148 /*TInfo=*/nullptr,
6149 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006150 /*Mutable=*/false,
6151 ICIS_NoInit);
6152 Field->setAccess(AS_public);
6153 VaListDecl->addDecl(Field);
6154
6155 // };
6156 VaListDecl->completeDefinition();
6157
6158 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006159 QualType T = Context->getRecordType(VaListDecl);
6160 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006161}
6162
Ulrich Weigand47445072013-05-06 16:26:41 +00006163static TypedefDecl *
6164CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6165 // typedef struct __va_list_tag {
6166 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006167 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006168 VaListTagDecl->startDefinition();
6169
6170 const size_t NumFields = 4;
6171 QualType FieldTypes[NumFields];
6172 const char *FieldNames[NumFields];
6173
6174 // long __gpr;
6175 FieldTypes[0] = Context->LongTy;
6176 FieldNames[0] = "__gpr";
6177
6178 // long __fpr;
6179 FieldTypes[1] = Context->LongTy;
6180 FieldNames[1] = "__fpr";
6181
6182 // void *__overflow_arg_area;
6183 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6184 FieldNames[2] = "__overflow_arg_area";
6185
6186 // void *__reg_save_area;
6187 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6188 FieldNames[3] = "__reg_save_area";
6189
6190 // Create fields
6191 for (unsigned i = 0; i < NumFields; ++i) {
6192 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6193 VaListTagDecl,
6194 SourceLocation(),
6195 SourceLocation(),
6196 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006197 FieldTypes[i], /*TInfo=*/nullptr,
6198 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006199 /*Mutable=*/false,
6200 ICIS_NoInit);
6201 Field->setAccess(AS_public);
6202 VaListTagDecl->addDecl(Field);
6203 }
6204 VaListTagDecl->completeDefinition();
6205 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6206 Context->VaListTagTy = VaListTagType;
6207
6208 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006209 TypedefDecl *VaListTagTypedefDecl =
6210 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006211 QualType VaListTagTypedefType =
6212 Context->getTypedefType(VaListTagTypedefDecl);
6213
6214 // typedef __va_list_tag __builtin_va_list[1];
6215 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6216 QualType VaListTagArrayType
6217 = Context->getConstantArrayType(VaListTagTypedefType,
6218 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006219
Alp Toker56b5cc92013-12-15 10:36:26 +00006220 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006221}
6222
Meador Inge5d3fb222012-06-16 03:34:49 +00006223static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6224 TargetInfo::BuiltinVaListKind Kind) {
6225 switch (Kind) {
6226 case TargetInfo::CharPtrBuiltinVaList:
6227 return CreateCharPtrBuiltinVaListDecl(Context);
6228 case TargetInfo::VoidPtrBuiltinVaList:
6229 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006230 case TargetInfo::AArch64ABIBuiltinVaList:
6231 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006232 case TargetInfo::PowerABIBuiltinVaList:
6233 return CreatePowerABIBuiltinVaListDecl(Context);
6234 case TargetInfo::X86_64ABIBuiltinVaList:
6235 return CreateX86_64ABIBuiltinVaListDecl(Context);
6236 case TargetInfo::PNaClABIBuiltinVaList:
6237 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006238 case TargetInfo::AAPCSABIBuiltinVaList:
6239 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006240 case TargetInfo::SystemZBuiltinVaList:
6241 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006242 }
6243
6244 llvm_unreachable("Unhandled __builtin_va_list type kind");
6245}
6246
6247TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006248 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006249 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006250 assert(BuiltinVaListDecl->isImplicit());
6251 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006252
6253 return BuiltinVaListDecl;
6254}
6255
Meador Ingecfb60902012-07-01 15:57:25 +00006256QualType ASTContext::getVaListTagType() const {
6257 // Force the creation of VaListTagTy by building the __builtin_va_list
6258 // declaration.
6259 if (VaListTagTy.isNull())
6260 (void) getBuiltinVaListDecl();
6261
6262 return VaListTagTy;
6263}
6264
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006265void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006266 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006267 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006268
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006269 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006270}
6271
John McCalld28ae272009-12-02 08:04:21 +00006272/// \brief Retrieve the template name that corresponds to a non-empty
6273/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006274TemplateName
6275ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6276 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006277 unsigned size = End - Begin;
6278 assert(size > 1 && "set is not overloaded!");
6279
6280 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6281 size * sizeof(FunctionTemplateDecl*));
6282 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6283
6284 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006285 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006286 NamedDecl *D = *I;
6287 assert(isa<FunctionTemplateDecl>(D) ||
6288 (isa<UsingShadowDecl>(D) &&
6289 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6290 *Storage++ = D;
6291 }
6292
6293 return TemplateName(OT);
6294}
6295
Douglas Gregordc572a32009-03-30 22:58:21 +00006296/// \brief Retrieve the template name that represents a qualified
6297/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006298TemplateName
6299ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6300 bool TemplateKeyword,
6301 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006302 assert(NNS && "Missing nested-name-specifier in qualified template name");
6303
Douglas Gregorc42075a2010-02-04 18:10:26 +00006304 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006305 llvm::FoldingSetNodeID ID;
6306 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6307
Craig Topper36250ad2014-05-12 05:36:57 +00006308 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006309 QualifiedTemplateName *QTN =
6310 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6311 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006312 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6313 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006314 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6315 }
6316
6317 return TemplateName(QTN);
6318}
6319
6320/// \brief Retrieve the template name that represents a dependent
6321/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006322TemplateName
6323ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6324 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006325 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006326 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006327
6328 llvm::FoldingSetNodeID ID;
6329 DependentTemplateName::Profile(ID, NNS, Name);
6330
Craig Topper36250ad2014-05-12 05:36:57 +00006331 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006332 DependentTemplateName *QTN =
6333 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6334
6335 if (QTN)
6336 return TemplateName(QTN);
6337
6338 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6339 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006340 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6341 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006342 } else {
6343 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006344 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6345 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006346 DependentTemplateName *CheckQTN =
6347 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6348 assert(!CheckQTN && "Dependent type name canonicalization broken");
6349 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006350 }
6351
6352 DependentTemplateNames.InsertNode(QTN, InsertPos);
6353 return TemplateName(QTN);
6354}
6355
Douglas Gregor71395fa2009-11-04 00:56:37 +00006356/// \brief Retrieve the template name that represents a dependent
6357/// template name such as \c MetaFun::template operator+.
6358TemplateName
6359ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006360 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006361 assert((!NNS || NNS->isDependent()) &&
6362 "Nested name specifier must be dependent");
6363
6364 llvm::FoldingSetNodeID ID;
6365 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006366
6367 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006368 DependentTemplateName *QTN
6369 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006370
6371 if (QTN)
6372 return TemplateName(QTN);
6373
6374 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6375 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006376 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6377 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006378 } else {
6379 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006380 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6381 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006382
6383 DependentTemplateName *CheckQTN
6384 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6385 assert(!CheckQTN && "Dependent template name canonicalization broken");
6386 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006387 }
6388
6389 DependentTemplateNames.InsertNode(QTN, InsertPos);
6390 return TemplateName(QTN);
6391}
6392
Douglas Gregor5590be02011-01-15 06:45:20 +00006393TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006394ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6395 TemplateName replacement) const {
6396 llvm::FoldingSetNodeID ID;
6397 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006398
6399 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006400 SubstTemplateTemplateParmStorage *subst
6401 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6402
6403 if (!subst) {
6404 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6405 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6406 }
6407
6408 return TemplateName(subst);
6409}
6410
6411TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006412ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6413 const TemplateArgument &ArgPack) const {
6414 ASTContext &Self = const_cast<ASTContext &>(*this);
6415 llvm::FoldingSetNodeID ID;
6416 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006417
6418 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006419 SubstTemplateTemplateParmPackStorage *Subst
6420 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6421
6422 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006423 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006424 ArgPack.pack_size(),
6425 ArgPack.pack_begin());
6426 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6427 }
6428
6429 return TemplateName(Subst);
6430}
6431
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006432/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006433/// TargetInfo, produce the corresponding type. The unsigned @p Type
6434/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006435CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006436 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006437 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006438 case TargetInfo::SignedChar: return SignedCharTy;
6439 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006440 case TargetInfo::SignedShort: return ShortTy;
6441 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6442 case TargetInfo::SignedInt: return IntTy;
6443 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6444 case TargetInfo::SignedLong: return LongTy;
6445 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6446 case TargetInfo::SignedLongLong: return LongLongTy;
6447 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6448 }
6449
David Blaikie83d382b2011-09-23 05:06:16 +00006450 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006451}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006452
6453//===----------------------------------------------------------------------===//
6454// Type Predicates.
6455//===----------------------------------------------------------------------===//
6456
Fariborz Jahanian96207692009-02-18 21:49:28 +00006457/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6458/// garbage collection attribute.
6459///
John McCall553d45a2011-01-12 00:34:59 +00006460Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006461 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006462 return Qualifiers::GCNone;
6463
David Blaikiebbafb8a2012-03-11 07:00:24 +00006464 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006465 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6466
6467 // Default behaviour under objective-C's gc is for ObjC pointers
6468 // (or pointers to them) be treated as though they were declared
6469 // as __strong.
6470 if (GCAttrs == Qualifiers::GCNone) {
6471 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6472 return Qualifiers::Strong;
6473 else if (Ty->isPointerType())
6474 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6475 } else {
6476 // It's not valid to set GC attributes on anything that isn't a
6477 // pointer.
6478#ifndef NDEBUG
6479 QualType CT = Ty->getCanonicalTypeInternal();
6480 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6481 CT = AT->getElementType();
6482 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6483#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006484 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006485 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006486}
6487
Chris Lattner49af6a42008-04-07 06:51:04 +00006488//===----------------------------------------------------------------------===//
6489// Type Compatibility Testing
6490//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006491
Mike Stump11289f42009-09-09 15:08:12 +00006492/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006493/// compatible.
6494static bool areCompatVectorTypes(const VectorType *LHS,
6495 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006496 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006497 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006498 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006499}
6500
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006501bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6502 QualType SecondVec) {
6503 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6504 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6505
6506 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6507 return true;
6508
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006509 // Treat Neon vector types and most AltiVec vector types as if they are the
6510 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006511 const VectorType *First = FirstVec->getAs<VectorType>();
6512 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006513 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006514 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006515 First->getVectorKind() != VectorType::AltiVecPixel &&
6516 First->getVectorKind() != VectorType::AltiVecBool &&
6517 Second->getVectorKind() != VectorType::AltiVecPixel &&
6518 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006519 return true;
6520
6521 return false;
6522}
6523
Steve Naroff8e6aee52009-07-23 01:01:38 +00006524//===----------------------------------------------------------------------===//
6525// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6526//===----------------------------------------------------------------------===//
6527
6528/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6529/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006530bool
6531ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6532 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006533 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006534 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006535 for (auto *PI : rProto->protocols())
6536 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006537 return true;
6538 return false;
6539}
6540
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006541/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6542/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006543bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6544 QualType rhs) {
6545 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6546 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6547 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6548
Aaron Ballman83731462014-03-17 16:14:00 +00006549 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006550 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006551 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006552 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6553 match = true;
6554 break;
6555 }
6556 }
6557 if (!match)
6558 return false;
6559 }
6560 return true;
6561}
6562
Steve Naroff8e6aee52009-07-23 01:01:38 +00006563/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6564/// ObjCQualifiedIDType.
6565bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6566 bool compare) {
6567 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006568 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006569 lhs->isObjCIdType() || lhs->isObjCClassType())
6570 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006571 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006572 rhs->isObjCIdType() || rhs->isObjCClassType())
6573 return true;
6574
6575 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006576 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006577
Steve Naroff8e6aee52009-07-23 01:01:38 +00006578 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006579
Steve Naroff8e6aee52009-07-23 01:01:38 +00006580 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006581 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006582 // make sure we check the class hierarchy.
6583 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006584 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006585 // when comparing an id<P> on lhs with a static type on rhs,
6586 // see if static class implements all of id's protocols, directly or
6587 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006588 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006589 return false;
6590 }
6591 }
6592 // If there are no qualifiers and no interface, we have an 'id'.
6593 return true;
6594 }
Mike Stump11289f42009-09-09 15:08:12 +00006595 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006596 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006597 bool match = false;
6598
6599 // when comparing an id<P> on lhs with a static type on rhs,
6600 // see if static class implements all of id's protocols, directly or
6601 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006602 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006603 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6604 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6605 match = true;
6606 break;
6607 }
6608 }
Mike Stump11289f42009-09-09 15:08:12 +00006609 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006610 // make sure we check the class hierarchy.
6611 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006612 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006613 // when comparing an id<P> on lhs with a static type on rhs,
6614 // see if static class implements all of id's protocols, directly or
6615 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006616 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006617 match = true;
6618 break;
6619 }
6620 }
6621 }
6622 if (!match)
6623 return false;
6624 }
Mike Stump11289f42009-09-09 15:08:12 +00006625
Steve Naroff8e6aee52009-07-23 01:01:38 +00006626 return true;
6627 }
Mike Stump11289f42009-09-09 15:08:12 +00006628
Steve Naroff8e6aee52009-07-23 01:01:38 +00006629 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6630 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6631
Mike Stump11289f42009-09-09 15:08:12 +00006632 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006633 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006634 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006635 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006636 bool match = false;
6637
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006638 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006639 // see if static class implements all of id's protocols, directly or
6640 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006641 // First, lhs protocols in the qualifier list must be found, direct
6642 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006643 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006644 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6645 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6646 match = true;
6647 break;
6648 }
6649 }
6650 if (!match)
6651 return false;
6652 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006653
6654 // Static class's protocols, or its super class or category protocols
6655 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6656 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6657 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6658 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6659 // This is rather dubious but matches gcc's behavior. If lhs has
6660 // no type qualifier and its class has no static protocol(s)
6661 // assume that it is mismatch.
6662 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6663 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006664 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006665 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006666 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006667 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6668 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6669 match = true;
6670 break;
6671 }
6672 }
6673 if (!match)
6674 return false;
6675 }
6676 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006677 return true;
6678 }
6679 return false;
6680}
6681
Eli Friedman47f77112008-08-22 00:56:42 +00006682/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006683/// compatible for assignment from RHS to LHS. This handles validation of any
6684/// protocol qualifiers on the LHS or RHS.
6685///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006686bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6687 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006688 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6689 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6690
Steve Naroff1329fa02009-07-15 18:40:39 +00006691 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006692 if (LHS->isObjCUnqualifiedIdOrClass() ||
6693 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006694 return true;
6695
John McCall8b07ec22010-05-15 11:32:37 +00006696 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006697 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6698 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006699 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006700
6701 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6702 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6703 QualType(RHSOPT,0));
6704
John McCall8b07ec22010-05-15 11:32:37 +00006705 // If we have 2 user-defined types, fall into that path.
6706 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006707 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006708
Steve Naroff8e6aee52009-07-23 01:01:38 +00006709 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006710}
6711
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006712/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006713/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006714/// arguments in block literals. When passed as arguments, passing 'A*' where
6715/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6716/// not OK. For the return type, the opposite is not OK.
6717bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6718 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006719 const ObjCObjectPointerType *RHSOPT,
6720 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006721 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006722 return true;
6723
6724 if (LHSOPT->isObjCBuiltinType()) {
6725 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6726 }
6727
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006728 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006729 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6730 QualType(RHSOPT,0),
6731 false);
6732
6733 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6734 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6735 if (LHS && RHS) { // We have 2 user-defined types.
6736 if (LHS != RHS) {
6737 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006738 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006739 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006740 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006741 }
6742 else
6743 return true;
6744 }
6745 return false;
6746}
6747
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006748/// getIntersectionOfProtocols - This routine finds the intersection of set
6749/// of protocols inherited from two distinct objective-c pointer objects.
6750/// It is used to build composite qualifier list of the composite type of
6751/// the conditional expression involving two objective-c pointer objects.
6752static
6753void getIntersectionOfProtocols(ASTContext &Context,
6754 const ObjCObjectPointerType *LHSOPT,
6755 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006756 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006757
John McCall8b07ec22010-05-15 11:32:37 +00006758 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6759 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6760 assert(LHS->getInterface() && "LHS must have an interface base");
6761 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006762
6763 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6764 unsigned LHSNumProtocols = LHS->getNumProtocols();
6765 if (LHSNumProtocols > 0)
6766 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6767 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006768 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006769 Context.CollectInheritedProtocols(LHS->getInterface(),
6770 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006771 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6772 LHSInheritedProtocols.end());
6773 }
6774
6775 unsigned RHSNumProtocols = RHS->getNumProtocols();
6776 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006777 ObjCProtocolDecl **RHSProtocols =
6778 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006779 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6780 if (InheritedProtocolSet.count(RHSProtocols[i]))
6781 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006782 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006783 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006784 Context.CollectInheritedProtocols(RHS->getInterface(),
6785 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006786 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6787 if (InheritedProtocolSet.count(ProtDecl))
6788 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006789 }
6790}
6791
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006792/// areCommonBaseCompatible - Returns common base class of the two classes if
6793/// one found. Note that this is O'2 algorithm. But it will be called as the
6794/// last type comparison in a ?-exp of ObjC pointer types before a
6795/// warning is issued. So, its invokation is extremely rare.
6796QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006797 const ObjCObjectPointerType *Lptr,
6798 const ObjCObjectPointerType *Rptr) {
6799 const ObjCObjectType *LHS = Lptr->getObjectType();
6800 const ObjCObjectType *RHS = Rptr->getObjectType();
6801 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6802 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006803 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006804 return QualType();
6805
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006806 do {
John McCall8b07ec22010-05-15 11:32:37 +00006807 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006808 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006809 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006810 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6811
6812 QualType Result = QualType(LHS, 0);
6813 if (!Protocols.empty())
6814 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6815 Result = getObjCObjectPointerType(Result);
6816 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006817 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006818 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006819
6820 return QualType();
6821}
6822
John McCall8b07ec22010-05-15 11:32:37 +00006823bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6824 const ObjCObjectType *RHS) {
6825 assert(LHS->getInterface() && "LHS is not an interface type");
6826 assert(RHS->getInterface() && "RHS is not an interface type");
6827
Chris Lattner49af6a42008-04-07 06:51:04 +00006828 // Verify that the base decls are compatible: the RHS must be a subclass of
6829 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006830 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006831 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006832
Chris Lattner49af6a42008-04-07 06:51:04 +00006833 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6834 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006835 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006836 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006837
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006838 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6839 // More detailed analysis is required.
6840 // OK, if LHS is same or a superclass of RHS *and*
6841 // this LHS, or as RHS's super class is assignment compatible with LHS.
6842 bool IsSuperClass =
6843 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6844 if (IsSuperClass) {
6845 // OK if conversion of LHS to SuperClass results in narrowing of types
6846 // ; i.e., SuperClass may implement at least one of the protocols
6847 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6848 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6849 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6850 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6851 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6852 // qualifiers.
6853 for (auto *RHSPI : RHS->quals())
6854 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6855 // If there is no protocols associated with RHS, it is not a match.
6856 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006857 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006858
6859 for (const auto *LHSProto : LHS->quals()) {
6860 bool SuperImplementsProtocol = false;
6861 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6862 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6863 SuperImplementsProtocol = true;
6864 break;
6865 }
6866 if (!SuperImplementsProtocol)
6867 return false;
6868 }
6869 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006870 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006871 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006872}
6873
Steve Naroffb7605152009-02-12 17:52:19 +00006874bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6875 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006876 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6877 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006878
Steve Naroff7cae42b2009-07-10 23:34:53 +00006879 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006880 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006881
6882 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6883 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006884}
6885
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006886bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6887 return canAssignObjCInterfaces(
6888 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6889 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6890}
6891
Mike Stump11289f42009-09-09 15:08:12 +00006892/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006893/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006894/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006895/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006896bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6897 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006898 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006899 return hasSameType(LHS, RHS);
6900
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006901 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006902}
6903
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006904bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006905 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006906}
6907
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006908bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6909 return !mergeTypes(LHS, RHS, true).isNull();
6910}
6911
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006912/// mergeTransparentUnionType - if T is a transparent union type and a member
6913/// of T is compatible with SubType, return the merged type, else return
6914/// QualType()
6915QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6916 bool OfBlockPointer,
6917 bool Unqualified) {
6918 if (const RecordType *UT = T->getAsUnionType()) {
6919 RecordDecl *UD = UT->getDecl();
6920 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006921 for (const auto *I : UD->fields()) {
6922 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006923 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6924 if (!MT.isNull())
6925 return MT;
6926 }
6927 }
6928 }
6929
6930 return QualType();
6931}
6932
Alp Toker9cacbab2014-01-20 20:26:09 +00006933/// mergeFunctionParameterTypes - merge two types which appear as function
6934/// parameter types
6935QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6936 bool OfBlockPointer,
6937 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006938 // GNU extension: two types are compatible if they appear as a function
6939 // argument, one of the types is a transparent union type and the other
6940 // type is compatible with a union member
6941 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6942 Unqualified);
6943 if (!lmerge.isNull())
6944 return lmerge;
6945
6946 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6947 Unqualified);
6948 if (!rmerge.isNull())
6949 return rmerge;
6950
6951 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6952}
6953
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006954QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006955 bool OfBlockPointer,
6956 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006957 const FunctionType *lbase = lhs->getAs<FunctionType>();
6958 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006959 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6960 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006961 bool allLTypes = true;
6962 bool allRTypes = true;
6963
6964 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006965 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006966 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006967 QualType RHS = rbase->getReturnType();
6968 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006969 bool UnqualifiedResult = Unqualified;
6970 if (!UnqualifiedResult)
6971 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006972 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006973 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006974 else
Alp Toker314cc812014-01-25 16:55:45 +00006975 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006976 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006977 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006978
6979 if (Unqualified)
6980 retType = retType.getUnqualifiedType();
6981
Alp Toker314cc812014-01-25 16:55:45 +00006982 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6983 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006984 if (Unqualified) {
6985 LRetType = LRetType.getUnqualifiedType();
6986 RRetType = RRetType.getUnqualifiedType();
6987 }
6988
6989 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006990 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006991 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006992 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006993
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006994 // FIXME: double check this
6995 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6996 // rbase->getRegParmAttr() != 0 &&
6997 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006998 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6999 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007000
Douglas Gregor8c940862010-01-18 17:14:39 +00007001 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007002 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007003 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007004
John McCall8c6b56f2010-12-15 01:06:38 +00007005 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007006 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7007 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007008 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7009 return QualType();
7010
John McCall31168b02011-06-15 23:02:42 +00007011 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7012 return QualType();
7013
John McCall8c6b56f2010-12-15 01:06:38 +00007014 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7015 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007016
Rafael Espindola8778c282012-11-29 16:09:03 +00007017 if (lbaseInfo.getNoReturn() != NoReturn)
7018 allLTypes = false;
7019 if (rbaseInfo.getNoReturn() != NoReturn)
7020 allRTypes = false;
7021
John McCall31168b02011-06-15 23:02:42 +00007022 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007023
Eli Friedman47f77112008-08-22 00:56:42 +00007024 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007025 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7026 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007027 // Compatible functions must have the same number of parameters
7028 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007029 return QualType();
7030
7031 // Variadic and non-variadic functions aren't compatible
7032 if (lproto->isVariadic() != rproto->isVariadic())
7033 return QualType();
7034
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007035 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7036 return QualType();
7037
Fariborz Jahanian97676972011-09-28 21:52:05 +00007038 if (LangOpts.ObjCAutoRefCount &&
7039 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7040 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007041
7042 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007043 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007044 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7045 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7046 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7047 QualType paramType = mergeFunctionParameterTypes(
7048 lParamType, rParamType, OfBlockPointer, Unqualified);
7049 if (paramType.isNull())
7050 return QualType();
7051
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007052 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007053 paramType = paramType.getUnqualifiedType();
7054
7055 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007056 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007057 lParamType = lParamType.getUnqualifiedType();
7058 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007059 }
Alp Toker601b22c2014-01-21 23:35:24 +00007060
7061 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007062 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007063 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007064 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007065 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007066
Eli Friedman47f77112008-08-22 00:56:42 +00007067 if (allLTypes) return lhs;
7068 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007069
7070 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7071 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007072 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007073 }
7074
7075 if (lproto) allRTypes = false;
7076 if (rproto) allLTypes = false;
7077
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007078 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007079 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007080 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007081 if (proto->isVariadic()) return QualType();
7082 // Check that the types are compatible with the types that
7083 // would result from default argument promotions (C99 6.7.5.3p15).
7084 // The only types actually affected are promotable integer
7085 // types and floats, which would be passed as a different
7086 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007087 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7088 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007089
Eli Friedman448ce402012-08-30 00:44:15 +00007090 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007091 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007092 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7093 paramTy = Enum->getDecl()->getIntegerType();
7094 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007095 return QualType();
7096 }
Alp Toker601b22c2014-01-21 23:35:24 +00007097
7098 if (paramTy->isPromotableIntegerType() ||
7099 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007100 return QualType();
7101 }
7102
7103 if (allLTypes) return lhs;
7104 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007105
7106 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7107 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007108 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007109 }
7110
7111 if (allLTypes) return lhs;
7112 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007113 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007114}
7115
John McCall433c2e62013-03-21 00:10:07 +00007116/// Given that we have an enum type and a non-enum type, try to merge them.
7117static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7118 QualType other, bool isBlockReturnType) {
7119 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7120 // a signed integer type, or an unsigned integer type.
7121 // Compatibility is based on the underlying type, not the promotion
7122 // type.
7123 QualType underlyingType = ET->getDecl()->getIntegerType();
7124 if (underlyingType.isNull()) return QualType();
7125 if (Context.hasSameType(underlyingType, other))
7126 return other;
7127
7128 // In block return types, we're more permissive and accept any
7129 // integral type of the same size.
7130 if (isBlockReturnType && other->isIntegerType() &&
7131 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7132 return other;
7133
7134 return QualType();
7135}
7136
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007137QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007138 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007139 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007140 // C++ [expr]: If an expression initially has the type "reference to T", the
7141 // type is adjusted to "T" prior to any further analysis, the expression
7142 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007143 // expression is an lvalue unless the reference is an rvalue reference and
7144 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007145 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7146 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007147
7148 if (Unqualified) {
7149 LHS = LHS.getUnqualifiedType();
7150 RHS = RHS.getUnqualifiedType();
7151 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007152
Eli Friedman47f77112008-08-22 00:56:42 +00007153 QualType LHSCan = getCanonicalType(LHS),
7154 RHSCan = getCanonicalType(RHS);
7155
7156 // If two types are identical, they are compatible.
7157 if (LHSCan == RHSCan)
7158 return LHS;
7159
John McCall8ccfcb52009-09-24 19:53:00 +00007160 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007161 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7162 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007163 if (LQuals != RQuals) {
7164 // If any of these qualifiers are different, we have a type
7165 // mismatch.
7166 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007167 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7168 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007169 return QualType();
7170
7171 // Exactly one GC qualifier difference is allowed: __strong is
7172 // okay if the other type has no GC qualifier but is an Objective
7173 // C object pointer (i.e. implicitly strong by default). We fix
7174 // this by pretending that the unqualified type was actually
7175 // qualified __strong.
7176 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7177 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7178 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7179
7180 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7181 return QualType();
7182
7183 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7184 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7185 }
7186 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7187 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7188 }
Eli Friedman47f77112008-08-22 00:56:42 +00007189 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007190 }
7191
7192 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007193
Eli Friedmandcca6332009-06-01 01:22:52 +00007194 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7195 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007196
Chris Lattnerfd652912008-01-14 05:45:46 +00007197 // We want to consider the two function types to be the same for these
7198 // comparisons, just force one to the other.
7199 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7200 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007201
7202 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007203 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7204 LHSClass = Type::ConstantArray;
7205 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7206 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007207
John McCall8b07ec22010-05-15 11:32:37 +00007208 // ObjCInterfaces are just specialized ObjCObjects.
7209 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7210 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7211
Nate Begemance4d7fc2008-04-18 23:10:10 +00007212 // Canonicalize ExtVector -> Vector.
7213 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7214 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007215
Chris Lattner95554662008-04-07 05:43:21 +00007216 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007217 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007218 // Note that we only have special rules for turning block enum
7219 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007220 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007221 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007222 }
John McCall9dd450b2009-09-21 23:43:11 +00007223 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007224 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007225 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007226 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007227 if (OfBlockPointer && !BlockReturnType) {
7228 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7229 return LHS;
7230 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7231 return RHS;
7232 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007233
Eli Friedman47f77112008-08-22 00:56:42 +00007234 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007235 }
Eli Friedman47f77112008-08-22 00:56:42 +00007236
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007237 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007238 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007239#define TYPE(Class, Base)
7240#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007241#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007242#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7243#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7244#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007245 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007246
Richard Smith27d807c2013-04-30 13:56:41 +00007247 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007248 case Type::LValueReference:
7249 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007250 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007251 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007252
John McCall8b07ec22010-05-15 11:32:37 +00007253 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007254 case Type::IncompleteArray:
7255 case Type::VariableArray:
7256 case Type::FunctionProto:
7257 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007258 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007259
Chris Lattnerfd652912008-01-14 05:45:46 +00007260 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007261 {
7262 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007263 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7264 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007265 if (Unqualified) {
7266 LHSPointee = LHSPointee.getUnqualifiedType();
7267 RHSPointee = RHSPointee.getUnqualifiedType();
7268 }
7269 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7270 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007271 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007272 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007273 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007274 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007275 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007276 return getPointerType(ResultType);
7277 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007278 case Type::BlockPointer:
7279 {
7280 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007281 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7282 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007283 if (Unqualified) {
7284 LHSPointee = LHSPointee.getUnqualifiedType();
7285 RHSPointee = RHSPointee.getUnqualifiedType();
7286 }
7287 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7288 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007289 if (ResultType.isNull()) return QualType();
7290 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7291 return LHS;
7292 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7293 return RHS;
7294 return getBlockPointerType(ResultType);
7295 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007296 case Type::Atomic:
7297 {
7298 // Merge two pointer types, while trying to preserve typedef info
7299 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7300 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7301 if (Unqualified) {
7302 LHSValue = LHSValue.getUnqualifiedType();
7303 RHSValue = RHSValue.getUnqualifiedType();
7304 }
7305 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7306 Unqualified);
7307 if (ResultType.isNull()) return QualType();
7308 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7309 return LHS;
7310 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7311 return RHS;
7312 return getAtomicType(ResultType);
7313 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007314 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007315 {
7316 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7317 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7318 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7319 return QualType();
7320
7321 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7322 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007323 if (Unqualified) {
7324 LHSElem = LHSElem.getUnqualifiedType();
7325 RHSElem = RHSElem.getUnqualifiedType();
7326 }
7327
7328 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007329 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007330 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7331 return LHS;
7332 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7333 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007334 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7335 ArrayType::ArraySizeModifier(), 0);
7336 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7337 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007338 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7339 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007340 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7341 return LHS;
7342 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7343 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007344 if (LVAT) {
7345 // FIXME: This isn't correct! But tricky to implement because
7346 // the array's size has to be the size of LHS, but the type
7347 // has to be different.
7348 return LHS;
7349 }
7350 if (RVAT) {
7351 // FIXME: This isn't correct! But tricky to implement because
7352 // the array's size has to be the size of RHS, but the type
7353 // has to be different.
7354 return RHS;
7355 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007356 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7357 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007358 return getIncompleteArrayType(ResultType,
7359 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007360 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007361 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007362 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007363 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007364 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007365 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007366 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007367 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007368 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007369 case Type::Complex:
7370 // Distinct complex types are incompatible.
7371 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007372 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007373 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007374 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7375 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007376 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007377 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007378 case Type::ObjCObject: {
7379 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007380 // FIXME: This should be type compatibility, e.g. whether
7381 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007382 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7383 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7384 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007385 return LHS;
7386
Eli Friedman47f77112008-08-22 00:56:42 +00007387 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007388 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007389 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007390 if (OfBlockPointer) {
7391 if (canAssignObjCInterfacesInBlockPointer(
7392 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007393 RHS->getAs<ObjCObjectPointerType>(),
7394 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007395 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007396 return QualType();
7397 }
John McCall9dd450b2009-09-21 23:43:11 +00007398 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7399 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007400 return LHS;
7401
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007402 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007403 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007404 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007405
David Blaikie8a40f702012-01-17 06:56:22 +00007406 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007407}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007408
Fariborz Jahanian97676972011-09-28 21:52:05 +00007409bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7410 const FunctionProtoType *FromFunctionType,
7411 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007412 if (FromFunctionType->hasAnyConsumedParams() !=
7413 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007414 return false;
7415 FunctionProtoType::ExtProtoInfo FromEPI =
7416 FromFunctionType->getExtProtoInfo();
7417 FunctionProtoType::ExtProtoInfo ToEPI =
7418 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007419 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007420 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7421 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007422 return false;
7423 }
7424 return true;
7425}
7426
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007427/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7428/// 'RHS' attributes and returns the merged version; including for function
7429/// return types.
7430QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7431 QualType LHSCan = getCanonicalType(LHS),
7432 RHSCan = getCanonicalType(RHS);
7433 // If two types are identical, they are compatible.
7434 if (LHSCan == RHSCan)
7435 return LHS;
7436 if (RHSCan->isFunctionType()) {
7437 if (!LHSCan->isFunctionType())
7438 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007439 QualType OldReturnType =
7440 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007441 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007442 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007443 QualType ResReturnType =
7444 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7445 if (ResReturnType.isNull())
7446 return QualType();
7447 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7448 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7449 // In either case, use OldReturnType to build the new function type.
7450 const FunctionType *F = LHS->getAs<FunctionType>();
7451 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007452 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7453 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007454 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007455 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007456 return ResultType;
7457 }
7458 }
7459 return QualType();
7460 }
7461
7462 // If the qualifiers are different, the types can still be merged.
7463 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7464 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7465 if (LQuals != RQuals) {
7466 // If any of these qualifiers are different, we have a type mismatch.
7467 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7468 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7469 return QualType();
7470
7471 // Exactly one GC qualifier difference is allowed: __strong is
7472 // okay if the other type has no GC qualifier but is an Objective
7473 // C object pointer (i.e. implicitly strong by default). We fix
7474 // this by pretending that the unqualified type was actually
7475 // qualified __strong.
7476 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7477 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7478 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7479
7480 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7481 return QualType();
7482
7483 if (GC_L == Qualifiers::Strong)
7484 return LHS;
7485 if (GC_R == Qualifiers::Strong)
7486 return RHS;
7487 return QualType();
7488 }
7489
7490 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7491 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7492 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7493 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7494 if (ResQT == LHSBaseQT)
7495 return LHS;
7496 if (ResQT == RHSBaseQT)
7497 return RHS;
7498 }
7499 return QualType();
7500}
7501
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007502//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007503// Integer Predicates
7504//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007505
Jay Foad39c79802011-01-12 09:06:06 +00007506unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007507 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007508 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007509 if (T->isBooleanType())
7510 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007511 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007512 return (unsigned)getTypeSize(T);
7513}
7514
Abramo Bagnara13640492012-09-09 10:21:24 +00007515QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007516 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007517
7518 // Turn <4 x signed int> -> <4 x unsigned int>
7519 if (const VectorType *VTy = T->getAs<VectorType>())
7520 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007521 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007522
7523 // For enums, we return the unsigned version of the base type.
7524 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007525 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007526
7527 const BuiltinType *BTy = T->getAs<BuiltinType>();
7528 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007529 switch (BTy->getKind()) {
7530 case BuiltinType::Char_S:
7531 case BuiltinType::SChar:
7532 return UnsignedCharTy;
7533 case BuiltinType::Short:
7534 return UnsignedShortTy;
7535 case BuiltinType::Int:
7536 return UnsignedIntTy;
7537 case BuiltinType::Long:
7538 return UnsignedLongTy;
7539 case BuiltinType::LongLong:
7540 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007541 case BuiltinType::Int128:
7542 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007543 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007544 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007545 }
7546}
7547
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007548ASTMutationListener::~ASTMutationListener() { }
7549
Richard Smith1fa5d642013-05-11 05:45:24 +00007550void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7551 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007552
7553//===----------------------------------------------------------------------===//
7554// Builtin Type Computation
7555//===----------------------------------------------------------------------===//
7556
7557/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007558/// pointer over the consumed characters. This returns the resultant type. If
7559/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7560/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7561/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007562///
7563/// RequiresICE is filled in on return to indicate whether the value is required
7564/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007565static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007566 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007567 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007568 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007569 // Modifiers.
7570 int HowLong = 0;
7571 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007572 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007573
Chris Lattnerdc226c22010-10-01 22:42:38 +00007574 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007575 bool Done = false;
7576 while (!Done) {
7577 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007578 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007579 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007580 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007581 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007582 case 'S':
7583 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7584 assert(!Signed && "Can't use 'S' modifier multiple times!");
7585 Signed = true;
7586 break;
7587 case 'U':
7588 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007589 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007590 Unsigned = true;
7591 break;
7592 case 'L':
7593 assert(HowLong <= 2 && "Can't have LLLL modifier");
7594 ++HowLong;
7595 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007596 case 'W':
7597 // This modifier represents int64 type.
7598 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7599 switch (Context.getTargetInfo().getInt64Type()) {
7600 default:
7601 llvm_unreachable("Unexpected integer type");
7602 case TargetInfo::SignedLong:
7603 HowLong = 1;
7604 break;
7605 case TargetInfo::SignedLongLong:
7606 HowLong = 2;
7607 break;
7608 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007609 }
7610 }
7611
7612 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007613
Chris Lattnerecd79c62009-06-14 00:45:47 +00007614 // Read the base type.
7615 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007616 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007617 case 'v':
7618 assert(HowLong == 0 && !Signed && !Unsigned &&
7619 "Bad modifiers used with 'v'!");
7620 Type = Context.VoidTy;
7621 break;
Jack Carter24bef982013-08-15 15:16:57 +00007622 case 'h':
7623 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007624 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007625 Type = Context.HalfTy;
7626 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007627 case 'f':
7628 assert(HowLong == 0 && !Signed && !Unsigned &&
7629 "Bad modifiers used with 'f'!");
7630 Type = Context.FloatTy;
7631 break;
7632 case 'd':
7633 assert(HowLong < 2 && !Signed && !Unsigned &&
7634 "Bad modifiers used with 'd'!");
7635 if (HowLong)
7636 Type = Context.LongDoubleTy;
7637 else
7638 Type = Context.DoubleTy;
7639 break;
7640 case 's':
7641 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7642 if (Unsigned)
7643 Type = Context.UnsignedShortTy;
7644 else
7645 Type = Context.ShortTy;
7646 break;
7647 case 'i':
7648 if (HowLong == 3)
7649 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7650 else if (HowLong == 2)
7651 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7652 else if (HowLong == 1)
7653 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7654 else
7655 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7656 break;
7657 case 'c':
7658 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7659 if (Signed)
7660 Type = Context.SignedCharTy;
7661 else if (Unsigned)
7662 Type = Context.UnsignedCharTy;
7663 else
7664 Type = Context.CharTy;
7665 break;
7666 case 'b': // boolean
7667 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7668 Type = Context.BoolTy;
7669 break;
7670 case 'z': // size_t.
7671 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7672 Type = Context.getSizeType();
7673 break;
7674 case 'F':
7675 Type = Context.getCFConstantStringType();
7676 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007677 case 'G':
7678 Type = Context.getObjCIdType();
7679 break;
7680 case 'H':
7681 Type = Context.getObjCSelType();
7682 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007683 case 'M':
7684 Type = Context.getObjCSuperType();
7685 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007686 case 'a':
7687 Type = Context.getBuiltinVaListType();
7688 assert(!Type.isNull() && "builtin va list type not initialized!");
7689 break;
7690 case 'A':
7691 // This is a "reference" to a va_list; however, what exactly
7692 // this means depends on how va_list is defined. There are two
7693 // different kinds of va_list: ones passed by value, and ones
7694 // passed by reference. An example of a by-value va_list is
7695 // x86, where va_list is a char*. An example of by-ref va_list
7696 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7697 // we want this argument to be a char*&; for x86-64, we want
7698 // it to be a __va_list_tag*.
7699 Type = Context.getBuiltinVaListType();
7700 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007701 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007702 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007703 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007704 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007705 break;
7706 case 'V': {
7707 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007708 unsigned NumElements = strtoul(Str, &End, 10);
7709 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007710 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007711
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007712 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7713 RequiresICE, false);
7714 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007715
7716 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007717 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007718 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007719 break;
7720 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007721 case 'E': {
7722 char *End;
7723
7724 unsigned NumElements = strtoul(Str, &End, 10);
7725 assert(End != Str && "Missing vector size");
7726
7727 Str = End;
7728
7729 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7730 false);
7731 Type = Context.getExtVectorType(ElementType, NumElements);
7732 break;
7733 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007734 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007735 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7736 false);
7737 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007738 Type = Context.getComplexType(ElementType);
7739 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007740 }
7741 case 'Y' : {
7742 Type = Context.getPointerDiffType();
7743 break;
7744 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007745 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007746 Type = Context.getFILEType();
7747 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007748 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007749 return QualType();
7750 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007751 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007752 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007753 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007754 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007755 else
7756 Type = Context.getjmp_bufType();
7757
Mike Stump2adb4da2009-07-28 23:47:15 +00007758 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007759 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007760 return QualType();
7761 }
7762 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007763 case 'K':
7764 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7765 Type = Context.getucontext_tType();
7766
7767 if (Type.isNull()) {
7768 Error = ASTContext::GE_Missing_ucontext;
7769 return QualType();
7770 }
7771 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007772 case 'p':
7773 Type = Context.getProcessIDType();
7774 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007775 }
Mike Stump11289f42009-09-09 15:08:12 +00007776
Chris Lattnerdc226c22010-10-01 22:42:38 +00007777 // If there are modifiers and if we're allowed to parse them, go for it.
7778 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007779 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007780 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007781 default: Done = true; --Str; break;
7782 case '*':
7783 case '&': {
7784 // Both pointers and references can have their pointee types
7785 // qualified with an address space.
7786 char *End;
7787 unsigned AddrSpace = strtoul(Str, &End, 10);
7788 if (End != Str && AddrSpace != 0) {
7789 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7790 Str = End;
7791 }
7792 if (c == '*')
7793 Type = Context.getPointerType(Type);
7794 else
7795 Type = Context.getLValueReferenceType(Type);
7796 break;
7797 }
7798 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7799 case 'C':
7800 Type = Type.withConst();
7801 break;
7802 case 'D':
7803 Type = Context.getVolatileType(Type);
7804 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007805 case 'R':
7806 Type = Type.withRestrict();
7807 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007808 }
7809 }
Chris Lattner84733392010-10-01 07:13:18 +00007810
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007811 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007812 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007813
Chris Lattnerecd79c62009-06-14 00:45:47 +00007814 return Type;
7815}
7816
7817/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007818QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007819 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007820 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007821 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007822
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007823 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007824
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007825 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007826 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007827 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7828 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007829 if (Error != GE_None)
7830 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007831
7832 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7833
Chris Lattnerecd79c62009-06-14 00:45:47 +00007834 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007835 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007836 if (Error != GE_None)
7837 return QualType();
7838
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007839 // If this argument is required to be an IntegerConstantExpression and the
7840 // caller cares, fill in the bitmask we return.
7841 if (RequiresICE && IntegerConstantArgs)
7842 *IntegerConstantArgs |= 1 << ArgTypes.size();
7843
Chris Lattnerecd79c62009-06-14 00:45:47 +00007844 // Do array -> pointer decay. The builtin should use the decayed type.
7845 if (Ty->isArrayType())
7846 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007847
Chris Lattnerecd79c62009-06-14 00:45:47 +00007848 ArgTypes.push_back(Ty);
7849 }
7850
David Majnemerba3e5ec2015-03-13 18:26:17 +00007851 if (Id == Builtin::BI__GetExceptionInfo)
7852 return QualType();
7853
Chris Lattnerecd79c62009-06-14 00:45:47 +00007854 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7855 "'.' should only occur at end of builtin type list!");
7856
Reid Kleckner78af0702013-08-27 23:08:25 +00007857 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007858 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7859
7860 bool Variadic = (TypeStr[0] == '.');
7861
7862 // We really shouldn't be making a no-proto type here, especially in C++.
7863 if (ArgTypes.empty() && Variadic)
7864 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007865
John McCalldb40c7f2010-12-14 08:05:40 +00007866 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007867 EPI.ExtInfo = EI;
7868 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007869
Jordan Rose5c382722013-03-08 21:51:21 +00007870 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007871}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007872
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007873static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7874 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007875 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007876 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007877
Rafael Espindola3ae00052013-05-13 00:12:11 +00007878 GVALinkage External = GVA_StrongExternal;
7879 switch (FD->getTemplateSpecializationKind()) {
7880 case TSK_Undeclared:
7881 case TSK_ExplicitSpecialization:
7882 External = GVA_StrongExternal;
7883 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007884
Rafael Espindola3ae00052013-05-13 00:12:11 +00007885 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007886 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007887
David Majnemerc3d07332014-05-15 06:25:57 +00007888 // C++11 [temp.explicit]p10:
7889 // [ Note: The intent is that an inline function that is the subject of
7890 // an explicit instantiation declaration will still be implicitly
7891 // instantiated when used so that the body can be considered for
7892 // inlining, but that no out-of-line copy of the inline function would be
7893 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007894 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007895 return GVA_AvailableExternally;
7896
Rafael Espindola3ae00052013-05-13 00:12:11 +00007897 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007898 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007899 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007900 }
7901
7902 if (!FD->isInlined())
7903 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007904
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007905 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7906 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007907 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007908 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7909
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007910 // GNU or C99 inline semantics. Determine whether this symbol should be
7911 // externally visible.
7912 if (FD->isInlineDefinitionExternallyVisible())
7913 return External;
7914
7915 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007916 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007917 }
7918
David Majnemer54e3ba52014-04-02 23:17:29 +00007919 // Functions specified with extern and inline in -fms-compatibility mode
7920 // forcibly get emitted. While the body of the function cannot be later
7921 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00007922 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00007923 return GVA_StrongODR;
7924
David Majnemer27d69db2014-04-28 22:17:59 +00007925 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007926}
7927
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007928static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7929 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7930 // dllexport/dllimport on inline functions.
7931 if (D->hasAttr<DLLImportAttr>()) {
7932 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7933 return GVA_AvailableExternally;
7934 } else if (D->hasAttr<DLLExportAttr>()) {
7935 if (L == GVA_DiscardableODR)
7936 return GVA_StrongODR;
7937 }
7938 return L;
7939}
7940
7941GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7942 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7943 FD);
7944}
7945
7946static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7947 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007948 if (!VD->isExternallyVisible())
7949 return GVA_Internal;
7950
David Majnemer27d69db2014-04-28 22:17:59 +00007951 if (VD->isStaticLocal()) {
7952 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7953 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7954 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7955 LexicalContext = LexicalContext->getLexicalParent();
7956
Richard Smith9e2341d2015-03-23 03:25:59 +00007957 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00007958 // enclosing function.
7959 if (LexicalContext)
7960 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007961 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007962
7963 // GVA_StrongODR function linkage is stronger than what we need,
7964 // downgrade to GVA_DiscardableODR.
7965 // This allows us to discard the variable if we never end up needing it.
7966 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7967 : StaticLocalLinkage;
7968 }
7969
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007970 // MSVC treats in-class initialized static data members as definitions.
7971 // By giving them non-strong linkage, out-of-line definitions won't
7972 // cause link errors.
7973 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7974 return GVA_DiscardableODR;
7975
Richard Smith8809a0c2013-09-27 20:14:12 +00007976 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007977 case TSK_Undeclared:
7978 case TSK_ExplicitSpecialization:
7979 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007980
Rafael Espindola3ae00052013-05-13 00:12:11 +00007981 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007982 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007983
David Majnemer27d69db2014-04-28 22:17:59 +00007984 case TSK_ExplicitInstantiationDeclaration:
7985 return GVA_AvailableExternally;
7986
Rafael Espindola3ae00052013-05-13 00:12:11 +00007987 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007988 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007989 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007990
7991 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007992}
7993
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007994GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7995 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7996 VD);
7997}
7998
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007999bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008000 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8001 if (!VD->isFileVarDecl())
8002 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008003 // Global named register variables (GNU extension) are never emitted.
8004 if (VD->getStorageClass() == SC_Register)
8005 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008006 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8007 // We never need to emit an uninstantiated function template.
8008 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8009 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008010 } else if (isa<OMPThreadPrivateDecl>(D))
8011 return true;
8012 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008013 return false;
8014
8015 // If this is a member of a class template, we do not need to emit it.
8016 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008017 return false;
8018
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008019 // Weak references don't produce any output by themselves.
8020 if (D->hasAttr<WeakRefAttr>())
8021 return false;
8022
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008023 // Aliases and used decls are required.
8024 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8025 return true;
8026
8027 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8028 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008029 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008030 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008031
8032 // Constructors and destructors are required.
8033 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8034 return true;
8035
John McCall6bd2a892013-01-25 22:31:03 +00008036 // The key function for a class is required. This rule only comes
8037 // into play when inline functions can be key functions, though.
8038 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8039 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8040 const CXXRecordDecl *RD = MD->getParent();
8041 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8042 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8043 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8044 return true;
8045 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008046 }
8047 }
8048
8049 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8050
8051 // static, static inline, always_inline, and extern inline functions can
8052 // always be deferred. Normal inline functions can be deferred in C99/C++.
8053 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008054 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8055 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008056 return false;
8057 return true;
8058 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008059
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008060 const VarDecl *VD = cast<VarDecl>(D);
8061 assert(VD->isFileVarDecl() && "Expected file scoped var");
8062
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008063 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8064 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008065 return false;
8066
Richard Smitha0e5e542012-11-12 21:38:00 +00008067 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008068 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008069 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8070 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008071 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008072
Richard Smitha0e5e542012-11-12 21:38:00 +00008073 // Variables that have destruction with side-effects are required.
8074 if (VD->getType().isDestructedType())
8075 return true;
8076
8077 // Variables that have initialization with side-effects are required.
8078 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8079 return true;
8080
8081 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008082}
Charles Davis53c59df2010-08-16 03:33:14 +00008083
Reid Kleckner78af0702013-08-27 23:08:25 +00008084CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8085 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008086 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008087 if (IsCXXMethod)
8088 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008089
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008090 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8091
8092 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008093}
8094
Jay Foad39c79802011-01-12 09:06:06 +00008095bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008096 // Pass through to the C++ ABI object
8097 return ABI->isNearlyEmpty(RD);
8098}
8099
Reid Kleckner96f8f932014-02-05 17:27:08 +00008100VTableContextBase *ASTContext::getVTableContext() {
8101 if (!VTContext.get()) {
8102 if (Target->getCXXABI().isMicrosoft())
8103 VTContext.reset(new MicrosoftVTableContext(*this));
8104 else
8105 VTContext.reset(new ItaniumVTableContext(*this));
8106 }
8107 return VTContext.get();
8108}
8109
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008110MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008111 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008112 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008113 case TargetCXXABI::GenericItanium:
8114 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008115 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008116 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008117 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008118 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008119 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008120 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008121 }
David Blaikie83d382b2011-09-23 05:06:16 +00008122 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008123}
8124
Charles Davis53c59df2010-08-16 03:33:14 +00008125CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008126
8127size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008128 return ASTRecordLayouts.getMemorySize() +
8129 llvm::capacity_in_bytes(ObjCLayouts) +
8130 llvm::capacity_in_bytes(KeyFunctions) +
8131 llvm::capacity_in_bytes(ObjCImpls) +
8132 llvm::capacity_in_bytes(BlockVarCopyInits) +
8133 llvm::capacity_in_bytes(DeclAttrs) +
8134 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8135 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8136 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8137 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8138 llvm::capacity_in_bytes(OverriddenMethods) +
8139 llvm::capacity_in_bytes(Types) +
8140 llvm::capacity_in_bytes(VariableArrayTypes) +
8141 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008142}
Ted Kremenek540017e2011-10-06 05:00:56 +00008143
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008144/// getIntTypeForBitwidth -
8145/// sets integer QualTy according to specified details:
8146/// bitwidth, signed/unsigned.
8147/// Returns empty type if there is no appropriate target types.
8148QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8149 unsigned Signed) const {
8150 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8151 CanQualType QualTy = getFromTargetType(Ty);
8152 if (!QualTy && DestWidth == 128)
8153 return Signed ? Int128Ty : UnsignedInt128Ty;
8154 return QualTy;
8155}
8156
8157/// getRealTypeForBitwidth -
8158/// sets floating point QualTy according to specified bitwidth.
8159/// Returns empty type if there is no appropriate target types.
8160QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8161 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8162 switch (Ty) {
8163 case TargetInfo::Float:
8164 return FloatTy;
8165 case TargetInfo::Double:
8166 return DoubleTy;
8167 case TargetInfo::LongDouble:
8168 return LongDoubleTy;
8169 case TargetInfo::NoFloat:
8170 return QualType();
8171 }
8172
8173 llvm_unreachable("Unhandled TargetInfo::RealType value");
8174}
8175
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008176void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8177 if (Number > 1)
8178 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008179}
8180
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008181unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8182 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8183 MangleNumbers.find(ND);
8184 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008185}
8186
David Majnemer2206bf52014-03-05 08:57:59 +00008187void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8188 if (Number > 1)
8189 StaticLocalNumbers[VD] = Number;
8190}
8191
8192unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8193 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8194 StaticLocalNumbers.find(VD);
8195 return I != StaticLocalNumbers.end() ? I->second : 1;
8196}
8197
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008198MangleNumberingContext &
8199ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008200 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8201 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8202 if (!MCtx)
8203 MCtx = createMangleNumberingContext();
8204 return *MCtx;
8205}
8206
8207MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8208 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008209}
8210
David Majnemere7a818f2015-03-06 18:53:55 +00008211const CXXConstructorDecl *
8212ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8213 return ABI->getCopyConstructorForExceptionObject(
8214 cast<CXXRecordDecl>(RD->getFirstDecl()));
8215}
8216
8217void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8218 CXXConstructorDecl *CD) {
8219 return ABI->addCopyConstructorForExceptionObject(
8220 cast<CXXRecordDecl>(RD->getFirstDecl()),
8221 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8222}
8223
David Majnemerdfa6d202015-03-11 18:36:39 +00008224void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8225 unsigned ParmIdx, Expr *DAE) {
8226 ABI->addDefaultArgExprForConstructor(
8227 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8228}
8229
8230Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8231 unsigned ParmIdx) {
8232 return ABI->getDefaultArgExprForConstructor(
8233 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8234}
8235
Ted Kremenek540017e2011-10-06 05:00:56 +00008236void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8237 ParamIndices[D] = index;
8238}
8239
8240unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8241 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8242 assert(I != ParamIndices.end() &&
8243 "ParmIndices lacks entry set by ParmVarDecl");
8244 return I->second;
8245}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008246
Richard Smithe6c01442013-06-05 00:46:14 +00008247APValue *
8248ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8249 bool MayCreate) {
8250 assert(E && E->getStorageDuration() == SD_Static &&
8251 "don't need to cache the computed value for this temporary");
8252 if (MayCreate)
8253 return &MaterializedTemporaryValues[E];
8254
8255 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8256 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008257 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008258}
8259
Fariborz Jahanian615de762013-05-28 17:37:39 +00008260bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8261 const llvm::Triple &T = getTargetInfo().getTriple();
8262 if (!T.isOSDarwin())
8263 return false;
8264
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008265 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8266 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8267 return false;
8268
Fariborz Jahanian615de762013-05-28 17:37:39 +00008269 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8270 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8271 uint64_t Size = sizeChars.getQuantity();
8272 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8273 unsigned Align = alignChars.getQuantity();
8274 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8275 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8276}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008277
8278namespace {
8279
8280 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8281 /// parents as defined by the \c RecursiveASTVisitor.
8282 ///
8283 /// Note that the relationship described here is purely in terms of AST
8284 /// traversal - there are other relationships (for example declaration context)
8285 /// in the AST that are better modeled by special matchers.
8286 ///
8287 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8288 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8289
8290 public:
8291 /// \brief Builds and returns the translation unit's parent map.
8292 ///
8293 /// The caller takes ownership of the returned \c ParentMap.
8294 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8295 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8296 Visitor.TraverseDecl(&TU);
8297 return Visitor.Parents;
8298 }
8299
8300 private:
8301 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8302
8303 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8304 }
8305
8306 bool shouldVisitTemplateInstantiations() const {
8307 return true;
8308 }
8309 bool shouldVisitImplicitCode() const {
8310 return true;
8311 }
8312 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8313 // are not triggered during data recursion.
8314 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8315 return false;
8316 }
8317
8318 template <typename T>
8319 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008320 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008321 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008322 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008323 // FIXME: Currently we add the same parent multiple times, but only
8324 // when no memoization data is available for the type.
8325 // For example when we visit all subexpressions of template
8326 // instantiations; this is suboptimal, but benign: the only way to
8327 // visit those is with hasAncestor / hasParent, and those do not create
8328 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008329 // The plan is to enable DynTypedNode to be storable in a map or hash
8330 // map. The main problem there is to implement hash functions /
8331 // comparison operators for all types that DynTypedNode supports that
8332 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008333 auto &NodeOrVector = (*Parents)[Node];
8334 if (NodeOrVector.isNull()) {
8335 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008336 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008337 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8338 auto *Node =
8339 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8340 auto *Vector = new ASTContext::ParentVector(1, *Node);
8341 NodeOrVector = Vector;
8342 delete Node;
8343 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008344 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008345
8346 auto *Vector =
8347 NodeOrVector.template get<ASTContext::ParentVector *>();
8348 // Skip duplicates for types that have memoization data.
8349 // We must check that the type has memoization data before calling
8350 // std::find() because DynTypedNode::operator== can't compare all
8351 // types.
8352 bool Found = ParentStack.back().getMemoizationData() &&
8353 std::find(Vector->begin(), Vector->end(),
8354 ParentStack.back()) != Vector->end();
8355 if (!Found)
8356 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008357 }
8358 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008359 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8360 bool Result = (this ->* traverse) (Node);
8361 ParentStack.pop_back();
8362 return Result;
8363 }
8364
8365 bool TraverseDecl(Decl *DeclNode) {
8366 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8367 }
8368
8369 bool TraverseStmt(Stmt *StmtNode) {
8370 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8371 }
8372
8373 ASTContext::ParentMap *Parents;
8374 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8375
8376 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8377 };
8378
8379} // end namespace
8380
Benjamin Kramer07935292014-10-04 17:01:26 +00008381ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008382ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8383 assert(Node.getMemoizationData() &&
8384 "Invariant broken: only nodes that support memoization may be "
8385 "used in the parent map.");
8386 if (!AllParents) {
8387 // We always need to run over the whole translation unit, as
8388 // hasAncestor can escape any subtree.
8389 AllParents.reset(
8390 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8391 }
8392 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8393 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008394 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008395 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008396 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8397 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008398 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008399 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008400}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008401
8402bool
8403ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8404 const ObjCMethodDecl *MethodImpl) {
8405 // No point trying to match an unavailable/deprecated mothod.
8406 if (MethodDecl->hasAttr<UnavailableAttr>()
8407 || MethodDecl->hasAttr<DeprecatedAttr>())
8408 return false;
8409 if (MethodDecl->getObjCDeclQualifier() !=
8410 MethodImpl->getObjCDeclQualifier())
8411 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008412 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008413 return false;
8414
8415 if (MethodDecl->param_size() != MethodImpl->param_size())
8416 return false;
8417
8418 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8419 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8420 EF = MethodDecl->param_end();
8421 IM != EM && IF != EF; ++IM, ++IF) {
8422 const ParmVarDecl *DeclVar = (*IF);
8423 const ParmVarDecl *ImplVar = (*IM);
8424 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8425 return false;
8426 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8427 return false;
8428 }
8429 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8430
8431}
Richard Smith053f6c62014-05-16 23:01:30 +00008432
8433// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8434// doesn't include ASTContext.h
8435template
8436clang::LazyGenerationalUpdatePtr<
8437 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8438clang::LazyGenerationalUpdatePtr<
8439 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8440 const clang::ASTContext &Ctx, Decl *Value);