blob: a0b801748828d263bfa9eb2c43f5b006693d8430 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
330} // unnamed namespace
331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
429 ThisDeclInfo);
430 return CFC;
431
432}
433
Richard Smithb39b9d52013-05-21 05:24:00 +0000434comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000437}
438
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000439comments::FullComment *ASTContext::getCommentForDecl(
440 const Decl *D,
441 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000442 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000443 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449
450 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 return CFC;
455 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000456 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 }
458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (!RC) {
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000464 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000470 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000476 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000478 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000479 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000480 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000484 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000485 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
497 }
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000500 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000501 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510 continue;
511
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000519 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000520 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000521 if (Ty.isNull())
522 continue;
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
525 continue;
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
528 }
529 }
530 }
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000532 }
533
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000542 ParsedComments[Canonical] = FC;
543 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000544}
545
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000546void
547ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000552
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
557 P != PEnd; ++P) {
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559 ID.AddInteger(0);
560 ID.AddBoolean(TTP->isParameterPack());
561 continue;
562 }
563
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000566 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000568 if (NTTP->isExpandedParameterPack()) {
569 ID.AddBoolean(true);
570 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000575 } else
576 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 continue;
578 }
579
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581 ID.AddInteger(2);
582 Profile(ID, TTP);
583 }
584}
585
586TemplateTemplateParmDecl *
587ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000588 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000592 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595 if (Canonical)
596 return Canonical->getParam();
597
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
604 P != PEnd; ++P) {
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000608 SourceLocation(),
609 SourceLocation(),
610 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000611 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625 }
626
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000628 SourceLocation(),
629 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000630 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000631 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 T,
633 TInfo,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
662 CanonParams.data(),
663 CanonParams.size(),
664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +0000685 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000686 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000687 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000688 return CreateMicrosoftCXXABI(*this);
689 }
David Blaikie8a40f702012-01-17 06:56:22 +0000690 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000691}
692
Douglas Gregore8bbc122011-09-02 00:18:52 +0000693static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000694 const LangOptions &LOpts) {
695 if (LOpts.FakeAddressSpaceMap) {
696 // The fake address space map must have a distinct entry for each
697 // language-specific address space.
698 static const unsigned FakeAddrSpaceMap[] = {
699 1, // opencl_global
700 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000701 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000702 4, // opencl_generic
703 5, // cuda_device
704 6, // cuda_constant
705 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000706 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000707 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 }
711}
712
David Tweed31d09b02013-09-13 12:04:22 +0000713static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
714 const LangOptions &LangOpts) {
715 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000716 case LangOptions::ASMM_Target:
717 return TI.useAddressSpaceMapMangling();
718 case LangOptions::ASMM_On:
719 return true;
720 case LangOptions::ASMM_Off:
721 return false;
722 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000723 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000724}
725
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000726ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000727 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000728 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000729 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
730 DependentTemplateSpecializationTypes(this_()),
731 SubstTemplateTemplateParmPacks(this_()),
732 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
733 UInt128Decl(nullptr), Float128StubDecl(nullptr),
734 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
735 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
736 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
737 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
738 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
739 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
740 NullTypeSourceInfo(QualType()), FirstLocalImport(), LastLocalImport(),
741 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova0416102014-11-11 01:26:14 +0000742 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000743 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
744 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
745 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
746 Comments(SM), CommentsLoaded(false),
747 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000748 TUDecl = TranslationUnitDecl::Create(*this);
749}
750
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000751ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000752 ReleaseParentMapEntries();
753
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000757
Manuel Klimeka7328992013-06-03 13:51:33 +0000758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
763
Ted Kremenek076baeb2010-06-08 23:00:58 +0000764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
771 R->Destroy(*this);
772
Ted Kremenek076baeb2010-06-08 23:00:58 +0000773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000779
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
782 A != AEnd; ++A)
783 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000784
Reid Kleckner588c9372014-02-19 23:44:52 +0000785 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000786}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000787
Manuel Klimek95403e62014-05-21 13:28:59 +0000788void ASTContext::ReleaseParentMapEntries() {
789 if (!AllParents) return;
790 for (const auto &Entry : *AllParents) {
791 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
792 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
793 } else {
794 assert(Entry.second.is<ParentVector *>());
795 delete Entry.second.get<ParentVector *>();
796 }
797 }
798}
799
Douglas Gregor1a809332010-05-23 18:26:36 +0000800void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000801 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000802}
803
Mike Stump11289f42009-09-09 15:08:12 +0000804void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000805ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
806 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000807}
808
Chris Lattner4eb445d2007-01-26 01:27:23 +0000809void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000810 llvm::errs() << "\n*** AST Context Stats:\n";
811 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000812
Douglas Gregora30d0462009-05-26 14:40:08 +0000813 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000814#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000815#define ABSTRACT_TYPE(Name, Parent)
816#include "clang/AST/TypeNodes.def"
817 0 // Extra
818 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000819
Chris Lattner4eb445d2007-01-26 01:27:23 +0000820 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
821 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000822 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000823 }
824
Douglas Gregora30d0462009-05-26 14:40:08 +0000825 unsigned Idx = 0;
826 unsigned TotalBytes = 0;
827#define TYPE(Name, Parent) \
828 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000829 llvm::errs() << " " << counts[Idx] << " " << #Name \
830 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000831 TotalBytes += counts[Idx] * sizeof(Name##Type); \
832 ++Idx;
833#define ABSTRACT_TYPE(Name, Parent)
834#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
837
Douglas Gregor7454c562010-07-02 20:37:36 +0000838 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000839 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
840 << NumImplicitDefaultConstructors
841 << " implicit default constructors created\n";
842 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
843 << NumImplicitCopyConstructors
844 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000845 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
847 << NumImplicitMoveConstructors
848 << " implicit move constructors created\n";
849 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
850 << NumImplicitCopyAssignmentOperators
851 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000852 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
854 << NumImplicitMoveAssignmentOperators
855 << " implicit move assignment operators created\n";
856 llvm::errs() << NumImplicitDestructorsDeclared << "/"
857 << NumImplicitDestructors
858 << " implicit destructors created\n";
859
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000860 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000861 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000862 ExternalSource->PrintStats();
863 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000864
Douglas Gregor5b11d492010-07-25 17:53:33 +0000865 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000866}
867
Alp Toker2dea15b2013-12-17 01:22:38 +0000868RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
869 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000870 SourceLocation Loc;
871 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000872 if (getLangOpts().CPlusPlus)
873 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
874 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000875 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000876 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
877 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000878 NewDecl->setImplicit();
879 return NewDecl;
880}
881
882TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
883 StringRef Name) const {
884 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
885 TypedefDecl *NewDecl = TypedefDecl::Create(
886 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
887 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
888 NewDecl->setImplicit();
889 return NewDecl;
890}
891
Douglas Gregor801c99d2011-08-12 06:49:56 +0000892TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000893 if (!Int128Decl)
894 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000895 return Int128Decl;
896}
897
898TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000899 if (!UInt128Decl)
900 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000901 return UInt128Decl;
902}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000903
Nico Webere1687c52013-06-20 21:44:55 +0000904TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000905 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000906 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000907 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000908
Nico Webere1687c52013-06-20 21:44:55 +0000909 return Float128StubDecl;
910}
911
John McCall48f2d582009-10-23 23:03:21 +0000912void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000913 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000914 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000915 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000916}
917
Douglas Gregore8bbc122011-09-02 00:18:52 +0000918void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
919 assert((!this->Target || this->Target == &Target) &&
920 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000921 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregore8bbc122011-09-02 00:18:52 +0000923 this->Target = &Target;
924
925 ABI.reset(createCXXABI(Target));
926 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000927 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000928
Chris Lattner970e54e2006-11-12 00:37:36 +0000929 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000930 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000931
Chris Lattner970e54e2006-11-12 00:37:36 +0000932 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000933 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000934 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000935 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000936 InitBuiltinType(CharTy, BuiltinType::Char_S);
937 else
938 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000939 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000940 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
941 InitBuiltinType(ShortTy, BuiltinType::Short);
942 InitBuiltinType(IntTy, BuiltinType::Int);
943 InitBuiltinType(LongTy, BuiltinType::Long);
944 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000945
Chris Lattner970e54e2006-11-12 00:37:36 +0000946 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000947 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
948 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
949 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
950 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
951 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000952
Chris Lattner970e54e2006-11-12 00:37:36 +0000953 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000954 InitBuiltinType(FloatTy, BuiltinType::Float);
955 InitBuiltinType(DoubleTy, BuiltinType::Double);
956 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000957
Chris Lattnerf122cef2009-04-30 02:43:43 +0000958 // GNU extension, 128-bit integers.
959 InitBuiltinType(Int128Ty, BuiltinType::Int128);
960 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
961
Hans Wennborg0d81e012013-05-10 10:08:40 +0000962 // C++ 3.9.1p5
963 if (TargetInfo::isTypeSigned(Target.getWCharType()))
964 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
965 else // -fshort-wchar makes wchar_t be unsigned.
966 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
967 if (LangOpts.CPlusPlus && LangOpts.WChar)
968 WideCharTy = WCharTy;
969 else {
970 // C99 (or C++ using -fno-wchar).
971 WideCharTy = getFromTargetType(Target.getWCharType());
972 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000973
James Molloy36365542012-05-04 10:55:22 +0000974 WIntTy = getFromTargetType(Target.getWIntType());
975
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000976 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
977 InitBuiltinType(Char16Ty, BuiltinType::Char16);
978 else // C99
979 Char16Ty = getFromTargetType(Target.getChar16Type());
980
981 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
982 InitBuiltinType(Char32Ty, BuiltinType::Char32);
983 else // C99
984 Char32Ty = getFromTargetType(Target.getChar32Type());
985
Douglas Gregor4619e432008-12-05 23:32:09 +0000986 // Placeholder type for type-dependent expressions whose type is
987 // completely unknown. No code should ever check a type against
988 // DependentTy and users should never see it; however, it is here to
989 // help diagnose failures to properly check for type-dependent
990 // expressions.
991 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000992
John McCall36e7fe32010-10-12 00:20:44 +0000993 // Placeholder type for functions.
994 InitBuiltinType(OverloadTy, BuiltinType::Overload);
995
John McCall0009fcc2011-04-26 20:42:42 +0000996 // Placeholder type for bound members.
997 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
998
John McCall526ab472011-10-25 17:37:35 +0000999 // Placeholder type for pseudo-objects.
1000 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1001
John McCall31996342011-04-07 08:22:57 +00001002 // "any" type; useful for debugger-like clients.
1003 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1004
John McCall8a6b59a2011-10-17 18:09:15 +00001005 // Placeholder type for unbridged ARC casts.
1006 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1007
Eli Friedman34866c72012-08-31 00:14:07 +00001008 // Placeholder type for builtin functions.
1009 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1010
Chris Lattner970e54e2006-11-12 00:37:36 +00001011 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001012 FloatComplexTy = getComplexType(FloatTy);
1013 DoubleComplexTy = getComplexType(DoubleTy);
1014 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001015
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001016 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001017 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1018 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001019 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001020
1021 if (LangOpts.OpenCL) {
1022 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1023 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1024 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1025 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1026 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1027 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001028
Guy Benyei61054192013-02-07 10:55:47 +00001029 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001030 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001031 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001032
1033 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001034 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1035 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001036
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001037 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001038
1039 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001040
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001041 // void * type
1042 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001043
1044 // nullptr type (C++0x 2.14.7)
1045 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001046
1047 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1048 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001049
1050 // Builtin type used to help define __builtin_va_list.
1051 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001052}
1053
David Blaikie9c902b52011-09-25 23:23:43 +00001054DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001055 return SourceMgr.getDiagnostics();
1056}
1057
Douglas Gregor561eceb2010-08-30 16:49:28 +00001058AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1059 AttrVec *&Result = DeclAttrs[D];
1060 if (!Result) {
1061 void *Mem = Allocate(sizeof(AttrVec));
1062 Result = new (Mem) AttrVec;
1063 }
1064
1065 return *Result;
1066}
1067
1068/// \brief Erase the attributes corresponding to the given declaration.
1069void ASTContext::eraseDeclAttrs(const Decl *D) {
1070 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1071 if (Pos != DeclAttrs.end()) {
1072 Pos->second->~AttrVec();
1073 DeclAttrs.erase(Pos);
1074 }
1075}
1076
Larisse Voufo39a1e502013-08-06 01:03:05 +00001077// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001078MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001079ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001080 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001081 return getTemplateOrSpecializationInfo(Var)
1082 .dyn_cast<MemberSpecializationInfo *>();
1083}
1084
1085ASTContext::TemplateOrSpecializationInfo
1086ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1087 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1088 TemplateOrInstantiation.find(Var);
1089 if (Pos == TemplateOrInstantiation.end())
1090 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001091
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001092 return Pos->second;
1093}
1094
Mike Stump11289f42009-09-09 15:08:12 +00001095void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001096ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001097 TemplateSpecializationKind TSK,
1098 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001099 assert(Inst->isStaticDataMember() && "Not a static data member");
1100 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001101 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1102 Tmpl, TSK, PointOfInstantiation));
1103}
1104
1105void
1106ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1107 TemplateOrSpecializationInfo TSI) {
1108 assert(!TemplateOrInstantiation[Inst] &&
1109 "Already noted what the variable was instantiated from");
1110 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001111}
1112
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001113FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1114 const FunctionDecl *FD){
1115 assert(FD && "Specialization is 0");
1116 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001117 = ClassScopeSpecializationPattern.find(FD);
1118 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001119 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001120
1121 return Pos->second;
1122}
1123
1124void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1125 FunctionDecl *Pattern) {
1126 assert(FD && "Specialization is 0");
1127 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001128 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001129}
1130
John McCalle61f2ba2009-11-18 02:36:19 +00001131NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001132ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001133 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001134 = InstantiatedFromUsingDecl.find(UUD);
1135 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001136 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001137
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001138 return Pos->second;
1139}
1140
1141void
John McCallb96ec562009-12-04 22:46:56 +00001142ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1143 assert((isa<UsingDecl>(Pattern) ||
1144 isa<UnresolvedUsingValueDecl>(Pattern) ||
1145 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1146 "pattern decl is not a using decl");
1147 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1148 InstantiatedFromUsingDecl[Inst] = Pattern;
1149}
1150
1151UsingShadowDecl *
1152ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1153 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1154 = InstantiatedFromUsingShadowDecl.find(Inst);
1155 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001156 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001157
1158 return Pos->second;
1159}
1160
1161void
1162ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1163 UsingShadowDecl *Pattern) {
1164 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1165 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001166}
1167
Anders Carlsson5da84842009-09-01 04:26:58 +00001168FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1169 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1170 = InstantiatedFromUnnamedFieldDecl.find(Field);
1171 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001172 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001173
Anders Carlsson5da84842009-09-01 04:26:58 +00001174 return Pos->second;
1175}
1176
1177void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1178 FieldDecl *Tmpl) {
1179 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1180 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1181 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1182 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001183
Anders Carlsson5da84842009-09-01 04:26:58 +00001184 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1185}
1186
Douglas Gregor832940b2010-03-02 23:58:15 +00001187ASTContext::overridden_cxx_method_iterator
1188ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001191 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001192 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001193
1194 return Pos->second.begin();
1195}
1196
1197ASTContext::overridden_cxx_method_iterator
1198ASTContext::overridden_methods_end(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.end();
1205}
1206
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001207unsigned
1208ASTContext::overridden_methods_size(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());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001211 if (Pos == OverriddenMethods.end())
1212 return 0;
1213
1214 return Pos->second.size();
1215}
1216
Douglas Gregor832940b2010-03-02 23:58:15 +00001217void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1218 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001219 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001220 OverriddenMethods[Method].push_back(Overridden);
1221}
1222
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001223void ASTContext::getOverriddenMethods(
1224 const NamedDecl *D,
1225 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001226 assert(D);
1227
1228 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001229 Overridden.append(overridden_methods_begin(CXXMethod),
1230 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001231 return;
1232 }
1233
1234 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1235 if (!Method)
1236 return;
1237
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001238 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1239 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001240 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001241}
1242
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001243void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1244 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1245 assert(!Import->isFromASTFile() && "Non-local import declaration");
1246 if (!FirstLocalImport) {
1247 FirstLocalImport = Import;
1248 LastLocalImport = Import;
1249 return;
1250 }
1251
1252 LastLocalImport->NextLocalImport = Import;
1253 LastLocalImport = Import;
1254}
1255
Chris Lattner53cfe802007-07-18 17:52:12 +00001256//===----------------------------------------------------------------------===//
1257// Type Sizing and Analysis
1258//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001259
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001260/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1261/// scalar floating point type.
1262const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001263 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001264 assert(BT && "Not a floating point type!");
1265 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001266 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001267 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001268 case BuiltinType::Float: return Target->getFloatFormat();
1269 case BuiltinType::Double: return Target->getDoubleFormat();
1270 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001271 }
1272}
1273
Rafael Espindola71eccb32013-08-08 19:53:46 +00001274CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001275 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001276
John McCall94268702010-10-08 18:24:19 +00001277 bool UseAlignAttrOnly = false;
1278 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1279 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001280
John McCall94268702010-10-08 18:24:19 +00001281 // __attribute__((aligned)) can increase or decrease alignment
1282 // *except* on a struct or struct member, where it only increases
1283 // alignment unless 'packed' is also specified.
1284 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001285 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001286 // ignore that possibility; Sema should diagnose it.
1287 if (isa<FieldDecl>(D)) {
1288 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1289 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1290 } else {
1291 UseAlignAttrOnly = true;
1292 }
1293 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001294 else if (isa<FieldDecl>(D))
1295 UseAlignAttrOnly =
1296 D->hasAttr<PackedAttr>() ||
1297 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001298
John McCall4e819612011-01-20 07:57:12 +00001299 // If we're using the align attribute only, just ignore everything
1300 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001301 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001302 // do nothing
1303
John McCall94268702010-10-08 18:24:19 +00001304 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001305 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001306 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001307 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001308 T = RT->getPointeeType();
1309 else
1310 T = getPointerType(RT->getPointeeType());
1311 }
Richard Smithf6d70302014-06-10 23:34:28 +00001312 QualType BaseT = getBaseElementType(T);
1313 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001314 // Adjust alignments of declarations with array type by the
1315 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001316 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001317 unsigned MinWidth = Target->getLargeArrayMinWidth();
1318 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001319 if (isa<VariableArrayType>(arrayType))
1320 Align = std::max(Align, Target->getLargeArrayAlign());
1321 else if (isa<ConstantArrayType>(arrayType) &&
1322 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1323 Align = std::max(Align, Target->getLargeArrayAlign());
1324 }
John McCall33ddac02011-01-19 10:06:00 +00001325 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001326 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001327 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1328 if (VD->hasGlobalStorage())
1329 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1330 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001331 }
John McCall4e819612011-01-20 07:57:12 +00001332
1333 // Fields can be subject to extra alignment constraints, like if
1334 // the field is packed, the struct is packed, or the struct has a
1335 // a max-field-alignment constraint (#pragma pack). So calculate
1336 // the actual alignment of the field within the struct, and then
1337 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001338 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1339 const RecordDecl *Parent = Field->getParent();
1340 // We can only produce a sensible answer if the record is valid.
1341 if (!Parent->isInvalidDecl()) {
1342 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001343
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001344 // Start with the record's overall alignment.
1345 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001346
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001347 // Use the GCD of that and the offset within the record.
1348 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1349 if (Offset > 0) {
1350 // Alignment is always a power of 2, so the GCD will be a power of 2,
1351 // which means we get to do this crazy thing instead of Euclid's.
1352 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1353 if (LowBitOfOffset < FieldAlign)
1354 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1355 }
1356
1357 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001358 }
Charles Davis3fc51072010-02-23 04:52:00 +00001359 }
Chris Lattner68061312009-01-24 21:53:27 +00001360 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001361
Ken Dyckcc56c542011-01-15 18:38:59 +00001362 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001363}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001364
John McCallf1249922012-08-21 04:10:00 +00001365// getTypeInfoDataSizeInChars - Return the size of a type, in
1366// chars. If the type is a record, its data size is returned. This is
1367// the size of the memcpy that's performed when assigning this type
1368// using a trivial copy/move assignment operator.
1369std::pair<CharUnits, CharUnits>
1370ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1371 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1372
1373 // In C++, objects can sometimes be allocated into the tail padding
1374 // of a base-class subobject. We decide whether that's possible
1375 // during class layout, so here we can just trust the layout results.
1376 if (getLangOpts().CPlusPlus) {
1377 if (const RecordType *RT = T->getAs<RecordType>()) {
1378 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1379 sizeAndAlign.first = layout.getDataSize();
1380 }
1381 }
1382
1383 return sizeAndAlign;
1384}
1385
Richard Trieu04d2d942013-05-14 21:59:17 +00001386/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1387/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1388std::pair<CharUnits, CharUnits>
1389static getConstantArrayInfoInChars(const ASTContext &Context,
1390 const ConstantArrayType *CAT) {
1391 std::pair<CharUnits, CharUnits> EltInfo =
1392 Context.getTypeInfoInChars(CAT->getElementType());
1393 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001394 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1395 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001396 "Overflow in array type char size evaluation");
1397 uint64_t Width = EltInfo.first.getQuantity() * Size;
1398 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001399 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1400 Context.getTargetInfo().getPointerWidth(0) == 64)
1401 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001402 return std::make_pair(CharUnits::fromQuantity(Width),
1403 CharUnits::fromQuantity(Align));
1404}
1405
John McCall87fe5d52010-05-20 01:18:31 +00001406std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001407ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001408 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1409 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001410 TypeInfo Info = getTypeInfo(T);
1411 return std::make_pair(toCharUnitsFromBits(Info.Width),
1412 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001413}
1414
1415std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001416ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001417 return getTypeInfoInChars(T.getTypePtr());
1418}
1419
David Majnemer34b57492014-07-30 01:30:47 +00001420bool ASTContext::isAlignmentRequired(const Type *T) const {
1421 return getTypeInfo(T).AlignIsRequired;
1422}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001423
David Majnemer34b57492014-07-30 01:30:47 +00001424bool ASTContext::isAlignmentRequired(QualType T) const {
1425 return isAlignmentRequired(T.getTypePtr());
1426}
1427
1428TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001429 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1430 if (I != MemoizedTypeInfo.end())
1431 return I->second;
1432
1433 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1434 TypeInfo TI = getTypeInfoImpl(T);
1435 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001436 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001437}
1438
1439/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1440/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001441///
1442/// FIXME: Pointers into different addr spaces could have different sizes and
1443/// alignment requirements: getPointerInfo should take an AddrSpace, this
1444/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001445TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1446 uint64_t Width = 0;
1447 unsigned Align = 8;
1448 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001449 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001450#define TYPE(Class, Base)
1451#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001452#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001453#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001454#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1455 case Type::Class: \
1456 assert(!T->isDependentType() && "should not see dependent types here"); \
1457 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001458#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001459 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001460
Chris Lattner355332d2007-07-13 22:27:08 +00001461 case Type::FunctionNoProto:
1462 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001463 // GCC extension: alignof(function) = 32 bits
1464 Width = 0;
1465 Align = 32;
1466 break;
1467
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001468 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001469 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001470 Width = 0;
1471 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1472 break;
1473
Steve Naroff5c131802007-08-30 01:06:46 +00001474 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001475 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001476
David Majnemer34b57492014-07-30 01:30:47 +00001477 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001478 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001479 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001480 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001481 Width = EltInfo.Width * Size;
1482 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001483 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1484 getTargetInfo().getPointerWidth(0) == 64)
1485 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001486 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001487 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001488 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001489 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001490 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001491 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1492 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001493 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001494 // If the alignment is not a power of 2, round up to the next power of 2.
1495 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001496 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001497 Align = llvm::NextPowerOf2(Align);
1498 Width = llvm::RoundUpToAlignment(Width, Align);
1499 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001500 // Adjust the alignment based on the target max.
1501 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1502 if (TargetVectorAlign && TargetVectorAlign < Align)
1503 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001504 break;
1505 }
Chris Lattner647fb222007-07-18 18:26:58 +00001506
Chris Lattner7570e9c2008-03-08 08:52:55 +00001507 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001508 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001509 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001510 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001511 // GCC extension: alignof(void) = 8 bits.
1512 Width = 0;
1513 Align = 8;
1514 break;
1515
Chris Lattner6a4f7452007-12-19 19:23:28 +00001516 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001517 Width = Target->getBoolWidth();
1518 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001519 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001520 case BuiltinType::Char_S:
1521 case BuiltinType::Char_U:
1522 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001523 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001524 Width = Target->getCharWidth();
1525 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001526 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001527 case BuiltinType::WChar_S:
1528 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001529 Width = Target->getWCharWidth();
1530 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001531 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001532 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001533 Width = Target->getChar16Width();
1534 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001535 break;
1536 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001537 Width = Target->getChar32Width();
1538 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001539 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001540 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001541 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001542 Width = Target->getShortWidth();
1543 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001544 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001545 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001546 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001547 Width = Target->getIntWidth();
1548 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001549 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001550 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getLongWidth();
1553 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001555 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001556 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001557 Width = Target->getLongLongWidth();
1558 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001559 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001560 case BuiltinType::Int128:
1561 case BuiltinType::UInt128:
1562 Width = 128;
1563 Align = 128; // int128_t is 128-bit aligned on all targets.
1564 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001565 case BuiltinType::Half:
1566 Width = Target->getHalfWidth();
1567 Align = Target->getHalfAlign();
1568 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001569 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001570 Width = Target->getFloatWidth();
1571 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001572 break;
1573 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001574 Width = Target->getDoubleWidth();
1575 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001576 break;
1577 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001578 Width = Target->getLongDoubleWidth();
1579 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001580 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001581 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001582 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1583 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001584 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001585 case BuiltinType::ObjCId:
1586 case BuiltinType::ObjCClass:
1587 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001588 Width = Target->getPointerWidth(0);
1589 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001590 break;
Guy Benyei61054192013-02-07 10:55:47 +00001591 case BuiltinType::OCLSampler:
1592 // Samplers are modeled as integers.
1593 Width = Target->getIntWidth();
1594 Align = Target->getIntAlign();
1595 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001596 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001597 case BuiltinType::OCLImage1d:
1598 case BuiltinType::OCLImage1dArray:
1599 case BuiltinType::OCLImage1dBuffer:
1600 case BuiltinType::OCLImage2d:
1601 case BuiltinType::OCLImage2dArray:
1602 case BuiltinType::OCLImage3d:
1603 // Currently these types are pointers to opaque types.
1604 Width = Target->getPointerWidth(0);
1605 Align = Target->getPointerAlign(0);
1606 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001607 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001608 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001609 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001610 Width = Target->getPointerWidth(0);
1611 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001612 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001613 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001614 unsigned AS = getTargetAddressSpace(
1615 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001616 Width = Target->getPointerWidth(AS);
1617 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001618 break;
1619 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001620 case Type::LValueReference:
1621 case Type::RValueReference: {
1622 // alignof and sizeof should never enter this code path here, so we go
1623 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001624 unsigned AS = getTargetAddressSpace(
1625 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001626 Width = Target->getPointerWidth(AS);
1627 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001628 break;
1629 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001630 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001631 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001632 Width = Target->getPointerWidth(AS);
1633 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001634 break;
1635 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001636 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001637 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001638 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001639 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001640 }
Chris Lattner647fb222007-07-18 18:26:58 +00001641 case Type::Complex: {
1642 // Complex types have the same alignment as their elements, but twice the
1643 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001644 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1645 Width = EltInfo.Width * 2;
1646 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001647 break;
1648 }
John McCall8b07ec22010-05-15 11:32:37 +00001649 case Type::ObjCObject:
1650 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001651 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001652 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001653 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001654 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001655 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001656 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001657 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001658 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001659 break;
1660 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001661 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001662 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001663 const TagType *TT = cast<TagType>(T);
1664
1665 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001666 Width = 8;
1667 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001668 break;
1669 }
Mike Stump11289f42009-09-09 15:08:12 +00001670
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001671 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001672 return getTypeInfo(ET->getDecl()->getIntegerType());
1673
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001674 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001675 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001676 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001677 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001678 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001679 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001680
Chris Lattner63d2b362009-10-22 05:17:15 +00001681 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001682 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1683 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001684
Richard Smith30482bc2011-02-20 03:19:35 +00001685 case Type::Auto: {
1686 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001687 assert(!A->getDeducedType().isNull() &&
1688 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001689 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001690 }
1691
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001692 case Type::Paren:
1693 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1694
Douglas Gregoref462e62009-04-30 17:32:17 +00001695 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001696 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001697 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001698 // If the typedef has an aligned attribute on it, it overrides any computed
1699 // alignment we have. This violates the GCC documentation (which says that
1700 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001701 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001702 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001703 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001704 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001705 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001706 AlignIsRequired = Info.AlignIsRequired;
1707 }
David Majnemer34b57492014-07-30 01:30:47 +00001708 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001709 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001710 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001711
Abramo Bagnara6150c882010-05-11 21:36:43 +00001712 case Type::Elaborated:
1713 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001714
John McCall81904512011-01-06 01:58:22 +00001715 case Type::Attributed:
1716 return getTypeInfo(
1717 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1718
Eli Friedman0dfb8892011-10-06 23:00:33 +00001719 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001720 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001721 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1722 Width = Info.Width;
1723 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001724
1725 // If the size of the type doesn't exceed the platform's max
1726 // atomic promotion width, make the size and alignment more
1727 // favorable to atomic operations:
1728 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1729 // Round the size up to a power of 2.
1730 if (!llvm::isPowerOf2_64(Width))
1731 Width = llvm::NextPowerOf2(Width);
1732
1733 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001734 Align = static_cast<unsigned>(Width);
1735 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001736 }
1737
Douglas Gregoref462e62009-04-30 17:32:17 +00001738 }
Mike Stump11289f42009-09-09 15:08:12 +00001739
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001740 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001741 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001742}
1743
Ken Dyckcc56c542011-01-15 18:38:59 +00001744/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1745CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1746 return CharUnits::fromQuantity(BitSize / getCharWidth());
1747}
1748
Ken Dyckb0fcc592011-02-11 01:54:29 +00001749/// toBits - Convert a size in characters to a size in characters.
1750int64_t ASTContext::toBits(CharUnits CharSize) const {
1751 return CharSize.getQuantity() * getCharWidth();
1752}
1753
Ken Dyck8c89d592009-12-22 14:23:30 +00001754/// getTypeSizeInChars - Return the size of the specified type, in characters.
1755/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001756CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001757 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001758}
Jay Foad39c79802011-01-12 09:06:06 +00001759CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001760 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001761}
1762
Ken Dycka6046ab2010-01-26 17:25:18 +00001763/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001764/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001765CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001766 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001767}
Jay Foad39c79802011-01-12 09:06:06 +00001768CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001769 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001770}
1771
Chris Lattnera3402cd2009-01-27 18:08:34 +00001772/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1773/// type for the current target in bits. This can be different than the ABI
1774/// alignment in cases where it is beneficial for performance to overalign
1775/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001776unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001777 TypeInfo TI = getTypeInfo(T);
1778 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001779
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001780 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1781 return ABIAlign; // Never overalign on XCore.
1782
Eli Friedman7ab09572009-05-25 21:27:19 +00001783 // Double and long long should be naturally aligned if possible.
Richard Smithd7e1fe42014-06-10 23:43:44 +00001784 T = T->getBaseElementTypeUnsafe();
David Majnemer1d4db8f2014-02-24 23:43:27 +00001785 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001786 T = CT->getElementType().getTypePtr();
1787 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001788 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1789 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001790 // Don't increase the alignment if an alignment attribute was specified on a
1791 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001792 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001793 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001794
Chris Lattnera3402cd2009-01-27 18:08:34 +00001795 return ABIAlign;
1796}
1797
Ulrich Weigandfa806422013-05-06 16:23:57 +00001798/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1799/// to a global variable of the specified type.
1800unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1801 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1802}
1803
1804/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1805/// should be given to a global variable of the specified type.
1806CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1807 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1808}
1809
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001810/// DeepCollectObjCIvars -
1811/// This routine first collects all declared, but not synthesized, ivars in
1812/// super class and then collects all ivars, including those synthesized for
1813/// current class. This routine is used for implementation of current class
1814/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001815///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001816void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1817 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001818 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001819 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1820 DeepCollectObjCIvars(SuperClass, false, Ivars);
1821 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001822 for (const auto *I : OI->ivars())
1823 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001824 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001825 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001826 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001827 Iv= Iv->getNextIvar())
1828 Ivars.push_back(Iv);
1829 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001830}
1831
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001832/// CollectInheritedProtocols - Collect all protocols in current class and
1833/// those inherited by it.
1834void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001835 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001836 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001837 // We can use protocol_iterator here instead of
1838 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001839 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001840 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001841 for (auto *P : Proto->protocols()) {
1842 Protocols.insert(P->getCanonicalDecl());
1843 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001844 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001845 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001846
1847 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001848 for (const auto *Cat : OI->visible_categories())
1849 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001850
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001851 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1852 while (SD) {
1853 CollectInheritedProtocols(SD, Protocols);
1854 SD = SD->getSuperClass();
1855 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001856 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001857 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001858 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001859 for (const auto *P : Proto->protocols())
1860 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001861 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001862 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001863 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001864 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001865 for (const auto *P : Proto->protocols())
1866 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001867 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001868 }
1869}
1870
Jay Foad39c79802011-01-12 09:06:06 +00001871unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001872 unsigned count = 0;
1873 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001874 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001875 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001876
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001877 // Count ivar defined in this class's implementation. This
1878 // includes synthesized ivars.
1879 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001880 count += ImplDecl->ivar_size();
1881
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001882 return count;
1883}
1884
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001885bool ASTContext::isSentinelNullExpr(const Expr *E) {
1886 if (!E)
1887 return false;
1888
1889 // nullptr_t is always treated as null.
1890 if (E->getType()->isNullPtrType()) return true;
1891
1892 if (E->getType()->isAnyPointerType() &&
1893 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1894 Expr::NPC_ValueDependentIsNull))
1895 return true;
1896
1897 // Unfortunately, __null has type 'int'.
1898 if (isa<GNUNullExpr>(E)) return true;
1899
1900 return false;
1901}
1902
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001903/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1904ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1905 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1906 I = ObjCImpls.find(D);
1907 if (I != ObjCImpls.end())
1908 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001909 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001910}
1911/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1912ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1913 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1914 I = ObjCImpls.find(D);
1915 if (I != ObjCImpls.end())
1916 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001917 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001918}
1919
1920/// \brief Set the implementation of ObjCInterfaceDecl.
1921void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1922 ObjCImplementationDecl *ImplD) {
1923 assert(IFaceD && ImplD && "Passed null params");
1924 ObjCImpls[IFaceD] = ImplD;
1925}
1926/// \brief Set the implementation of ObjCCategoryDecl.
1927void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1928 ObjCCategoryImplDecl *ImplD) {
1929 assert(CatD && ImplD && "Passed null params");
1930 ObjCImpls[CatD] = ImplD;
1931}
1932
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001933const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1934 const NamedDecl *ND) const {
1935 if (const ObjCInterfaceDecl *ID =
1936 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001937 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001938 if (const ObjCCategoryDecl *CD =
1939 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001940 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001941 if (const ObjCImplDecl *IMD =
1942 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001943 return IMD->getClassInterface();
1944
Craig Topper36250ad2014-05-12 05:36:57 +00001945 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001946}
1947
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001948/// \brief Get the copy initialization expression of VarDecl,or NULL if
1949/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001950Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001951 assert(VD && "Passed null params");
1952 assert(VD->hasAttr<BlocksAttr>() &&
1953 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001954 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001955 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001956 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001957}
1958
1959/// \brief Set the copy inialization expression of a block var decl.
1960void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1961 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001962 assert(VD->hasAttr<BlocksAttr>() &&
1963 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001964 BlockVarCopyInits[VD] = Init;
1965}
1966
John McCallbcd03502009-12-07 02:54:59 +00001967TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001968 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001969 if (!DataSize)
1970 DataSize = TypeLoc::getFullDataSizeForType(T);
1971 else
1972 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001973 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001974
John McCallbcd03502009-12-07 02:54:59 +00001975 TypeSourceInfo *TInfo =
1976 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1977 new (TInfo) TypeSourceInfo(T);
1978 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001979}
1980
John McCallbcd03502009-12-07 02:54:59 +00001981TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001982 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001983 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001984 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001985 return DI;
1986}
1987
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001988const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001989ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00001990 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001991}
1992
1993const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001994ASTContext::getASTObjCImplementationLayout(
1995 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001996 return getObjCLayout(D->getClassInterface(), D);
1997}
1998
Chris Lattner983a8bb2007-07-13 22:13:22 +00001999//===----------------------------------------------------------------------===//
2000// Type creation/memoization methods
2001//===----------------------------------------------------------------------===//
2002
Jay Foad39c79802011-01-12 09:06:06 +00002003QualType
John McCall33ddac02011-01-19 10:06:00 +00002004ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2005 unsigned fastQuals = quals.getFastQualifiers();
2006 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002007
2008 // Check if we've already instantiated this type.
2009 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002010 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002011 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002012 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2013 assert(eq->getQualifiers() == quals);
2014 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002015 }
2016
John McCall33ddac02011-01-19 10:06:00 +00002017 // If the base type is not canonical, make the appropriate canonical type.
2018 QualType canon;
2019 if (!baseType->isCanonicalUnqualified()) {
2020 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002021 canonSplit.Quals.addConsistentQualifiers(quals);
2022 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002023
2024 // Re-find the insert position.
2025 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2026 }
2027
2028 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2029 ExtQualNodes.InsertNode(eq, insertPos);
2030 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002031}
2032
Jay Foad39c79802011-01-12 09:06:06 +00002033QualType
2034ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002035 QualType CanT = getCanonicalType(T);
2036 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002037 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002038
John McCall8ccfcb52009-09-24 19:53:00 +00002039 // If we are composing extended qualifiers together, merge together
2040 // into one ExtQuals node.
2041 QualifierCollector Quals;
2042 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002043
John McCall8ccfcb52009-09-24 19:53:00 +00002044 // If this type already has an address space specified, it cannot get
2045 // another one.
2046 assert(!Quals.hasAddressSpace() &&
2047 "Type cannot be in multiple addr spaces!");
2048 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002049
John McCall8ccfcb52009-09-24 19:53:00 +00002050 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002051}
2052
Chris Lattnerd60183d2009-02-18 22:53:11 +00002053QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002054 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002055 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002056 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002057 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002058
John McCall53fa7142010-12-24 02:08:15 +00002059 if (const PointerType *ptr = T->getAs<PointerType>()) {
2060 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002061 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002062 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2063 return getPointerType(ResultType);
2064 }
2065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
John McCall8ccfcb52009-09-24 19:53:00 +00002067 // If we are composing extended qualifiers together, merge together
2068 // into one ExtQuals node.
2069 QualifierCollector Quals;
2070 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002071
John McCall8ccfcb52009-09-24 19:53:00 +00002072 // If this type already has an ObjCGC specified, it cannot get
2073 // another one.
2074 assert(!Quals.hasObjCGCAttr() &&
2075 "Type cannot have multiple ObjCGCs!");
2076 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002077
John McCall8ccfcb52009-09-24 19:53:00 +00002078 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002079}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002080
John McCall4f5019e2010-12-19 02:44:49 +00002081const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2082 FunctionType::ExtInfo Info) {
2083 if (T->getExtInfo() == Info)
2084 return T;
2085
2086 QualType Result;
2087 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002088 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002089 } else {
2090 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2092 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002093 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002094 }
2095
2096 return cast<FunctionType>(Result.getTypePtr());
2097}
2098
Richard Smith2a7d4812013-05-04 07:00:32 +00002099void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2100 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002101 FD = FD->getMostRecentDecl();
2102 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002103 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2104 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002105 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002106 if (FunctionDecl *Next = FD->getPreviousDecl())
2107 FD = Next;
2108 else
2109 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002110 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002111 if (ASTMutationListener *L = getASTMutationListener())
2112 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002113}
2114
Richard Smith0b3a4622014-11-13 20:01:57 +00002115/// Get a function type and produce the equivalent function type with the
2116/// specified exception specification. Type sugar that can be present on a
2117/// declaration of a function with an exception specification is permitted
2118/// and preserved. Other type sugar (for instance, typedefs) is not.
2119static QualType getFunctionTypeWithExceptionSpec(
2120 ASTContext &Context, QualType Orig,
2121 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2122 // Might have some parens.
2123 if (auto *PT = dyn_cast<ParenType>(Orig))
2124 return Context.getParenType(
2125 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2126
2127 // Might have a calling-convention attribute.
2128 if (auto *AT = dyn_cast<AttributedType>(Orig))
2129 return Context.getAttributedType(
2130 AT->getAttrKind(),
2131 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2132 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2133 ESI));
2134
2135 // Anything else must be a function type. Rebuild it with the new exception
2136 // specification.
2137 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2138 return Context.getFunctionType(
2139 Proto->getReturnType(), Proto->getParamTypes(),
2140 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2141}
2142
2143void ASTContext::adjustExceptionSpec(
2144 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2145 bool AsWritten) {
2146 // Update the type.
2147 QualType Updated =
2148 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2149 FD->setType(Updated);
2150
2151 if (!AsWritten)
2152 return;
2153
2154 // Update the type in the type source information too.
2155 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2156 // If the type and the type-as-written differ, we may need to update
2157 // the type-as-written too.
2158 if (TSInfo->getType() != FD->getType())
2159 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2160
2161 // FIXME: When we get proper type location information for exceptions,
2162 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2163 // up the TypeSourceInfo;
2164 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2165 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2166 "TypeLoc size mismatch from updating exception specification");
2167 TSInfo->overrideType(Updated);
2168 }
2169}
2170
Chris Lattnerc6395932007-06-22 20:56:16 +00002171/// getComplexType - Return the uniqued reference to the type for a complex
2172/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002173QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002174 // Unique pointers, to guarantee there is only one pointer of a particular
2175 // structure.
2176 llvm::FoldingSetNodeID ID;
2177 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002178
Craig Topper36250ad2014-05-12 05:36:57 +00002179 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002180 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2181 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002182
Chris Lattnerc6395932007-06-22 20:56:16 +00002183 // If the pointee type isn't canonical, this won't be a canonical type either,
2184 // so fill in the canonical type field.
2185 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002186 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002187 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattnerc6395932007-06-22 20:56:16 +00002189 // Get the new insert position for the node we care about.
2190 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002191 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002192 }
John McCall90d1c2d2009-09-24 23:30:46 +00002193 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002194 Types.push_back(New);
2195 ComplexTypes.InsertNode(New, InsertPos);
2196 return QualType(New, 0);
2197}
2198
Chris Lattner970e54e2006-11-12 00:37:36 +00002199/// getPointerType - Return the uniqued reference to the type for a pointer to
2200/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002201QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002202 // Unique pointers, to guarantee there is only one pointer of a particular
2203 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002204 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002205 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002206
Craig Topper36250ad2014-05-12 05:36:57 +00002207 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002208 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002209 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattner7ccecb92006-11-12 08:50:50 +00002211 // If the pointee type isn't canonical, this won't be a canonical type either,
2212 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002213 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002214 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002215 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002216
Bob Wilsonc8541f22013-03-15 17:12:43 +00002217 // Get the new insert position for the node we care about.
2218 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002219 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002220 }
John McCall90d1c2d2009-09-24 23:30:46 +00002221 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002222 Types.push_back(New);
2223 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002224 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002225}
2226
Reid Kleckner0503a872013-12-05 01:23:43 +00002227QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2228 llvm::FoldingSetNodeID ID;
2229 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002230 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002231 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2232 if (AT)
2233 return QualType(AT, 0);
2234
2235 QualType Canonical = getCanonicalType(New);
2236
2237 // Get the new insert position for the node we care about.
2238 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002239 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002240
2241 AT = new (*this, TypeAlignment)
2242 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2243 Types.push_back(AT);
2244 AdjustedTypes.InsertNode(AT, InsertPos);
2245 return QualType(AT, 0);
2246}
2247
Reid Kleckner8a365022013-06-24 17:51:48 +00002248QualType ASTContext::getDecayedType(QualType T) const {
2249 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2250
Reid Kleckner8a365022013-06-24 17:51:48 +00002251 QualType Decayed;
2252
2253 // C99 6.7.5.3p7:
2254 // A declaration of a parameter as "array of type" shall be
2255 // adjusted to "qualified pointer to type", where the type
2256 // qualifiers (if any) are those specified within the [ and ] of
2257 // the array type derivation.
2258 if (T->isArrayType())
2259 Decayed = getArrayDecayedType(T);
2260
2261 // C99 6.7.5.3p8:
2262 // A declaration of a parameter as "function returning type"
2263 // shall be adjusted to "pointer to function returning type", as
2264 // in 6.3.2.1.
2265 if (T->isFunctionType())
2266 Decayed = getPointerType(T);
2267
Reid Kleckner0503a872013-12-05 01:23:43 +00002268 llvm::FoldingSetNodeID ID;
2269 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002270 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002271 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2272 if (AT)
2273 return QualType(AT, 0);
2274
Reid Kleckner8a365022013-06-24 17:51:48 +00002275 QualType Canonical = getCanonicalType(Decayed);
2276
2277 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002278 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002279 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002280
Reid Kleckner0503a872013-12-05 01:23:43 +00002281 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2282 Types.push_back(AT);
2283 AdjustedTypes.InsertNode(AT, InsertPos);
2284 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002285}
2286
Mike Stump11289f42009-09-09 15:08:12 +00002287/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002288/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002289QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002290 assert(T->isFunctionType() && "block of function types only");
2291 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002292 // structure.
2293 llvm::FoldingSetNodeID ID;
2294 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002295
Craig Topper36250ad2014-05-12 05:36:57 +00002296 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002297 if (BlockPointerType *PT =
2298 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2299 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002300
2301 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002302 // type either so fill in the canonical type field.
2303 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002304 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002305 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002306
Steve Naroffec33ed92008-08-27 16:04:49 +00002307 // Get the new insert position for the node we care about.
2308 BlockPointerType *NewIP =
2309 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002310 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002311 }
John McCall90d1c2d2009-09-24 23:30:46 +00002312 BlockPointerType *New
2313 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002314 Types.push_back(New);
2315 BlockPointerTypes.InsertNode(New, InsertPos);
2316 return QualType(New, 0);
2317}
2318
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002319/// getLValueReferenceType - Return the uniqued reference to the type for an
2320/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002321QualType
2322ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002323 assert(getCanonicalType(T) != OverloadTy &&
2324 "Unresolved overloaded function type");
2325
Bill Wendling3708c182007-05-27 10:15:43 +00002326 // Unique pointers, to guarantee there is only one pointer of a particular
2327 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002328 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002329 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002330
Craig Topper36250ad2014-05-12 05:36:57 +00002331 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002332 if (LValueReferenceType *RT =
2333 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002334 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002335
John McCallfc93cf92009-10-22 22:37:11 +00002336 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2337
Bill Wendling3708c182007-05-27 10:15:43 +00002338 // If the referencee type isn't canonical, this won't be a canonical type
2339 // either, so fill in the canonical type field.
2340 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002341 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2342 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2343 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002344
Bill Wendling3708c182007-05-27 10:15:43 +00002345 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002346 LValueReferenceType *NewIP =
2347 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002348 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002349 }
2350
John McCall90d1c2d2009-09-24 23:30:46 +00002351 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002352 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2353 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002354 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002355 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002356
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002357 return QualType(New, 0);
2358}
2359
2360/// getRValueReferenceType - Return the uniqued reference to the type for an
2361/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002362QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002363 // Unique pointers, to guarantee there is only one pointer of a particular
2364 // structure.
2365 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002366 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002367
Craig Topper36250ad2014-05-12 05:36:57 +00002368 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002369 if (RValueReferenceType *RT =
2370 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2371 return QualType(RT, 0);
2372
John McCallfc93cf92009-10-22 22:37:11 +00002373 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2374
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002375 // If the referencee type isn't canonical, this won't be a canonical type
2376 // either, so fill in the canonical type field.
2377 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002378 if (InnerRef || !T.isCanonical()) {
2379 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2380 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002381
2382 // Get the new insert position for the node we care about.
2383 RValueReferenceType *NewIP =
2384 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002385 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002386 }
2387
John McCall90d1c2d2009-09-24 23:30:46 +00002388 RValueReferenceType *New
2389 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002390 Types.push_back(New);
2391 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002392 return QualType(New, 0);
2393}
2394
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002395/// getMemberPointerType - Return the uniqued reference to the type for a
2396/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002397QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002398 // Unique pointers, to guarantee there is only one pointer of a particular
2399 // structure.
2400 llvm::FoldingSetNodeID ID;
2401 MemberPointerType::Profile(ID, T, Cls);
2402
Craig Topper36250ad2014-05-12 05:36:57 +00002403 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002404 if (MemberPointerType *PT =
2405 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2406 return QualType(PT, 0);
2407
2408 // If the pointee or class type isn't canonical, this won't be a canonical
2409 // type either, so fill in the canonical type field.
2410 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002411 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002412 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2413
2414 // Get the new insert position for the node we care about.
2415 MemberPointerType *NewIP =
2416 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002417 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002418 }
John McCall90d1c2d2009-09-24 23:30:46 +00002419 MemberPointerType *New
2420 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002421 Types.push_back(New);
2422 MemberPointerTypes.InsertNode(New, InsertPos);
2423 return QualType(New, 0);
2424}
2425
Mike Stump11289f42009-09-09 15:08:12 +00002426/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002427/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002428QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002429 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002430 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002431 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002432 assert((EltTy->isDependentType() ||
2433 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002434 "Constant array of VLAs is illegal!");
2435
Chris Lattnere2df3f92009-05-13 04:12:56 +00002436 // Convert the array size into a canonical width matching the pointer size for
2437 // the target.
2438 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002439 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002440 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002441
Chris Lattner23b7eb62007-06-15 23:05:46 +00002442 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002443 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002444
Craig Topper36250ad2014-05-12 05:36:57 +00002445 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002446 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002447 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002448 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002449
John McCall33ddac02011-01-19 10:06:00 +00002450 // If the element type isn't canonical or has qualifiers, this won't
2451 // be a canonical type either, so fill in the canonical type field.
2452 QualType Canon;
2453 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2454 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002455 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002456 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002457 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002458
Chris Lattner36f8e652007-01-27 08:31:04 +00002459 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002460 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002461 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002462 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002463 }
Mike Stump11289f42009-09-09 15:08:12 +00002464
John McCall90d1c2d2009-09-24 23:30:46 +00002465 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002466 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002467 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002468 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002469 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002470}
2471
John McCall06549462011-01-18 08:40:38 +00002472/// getVariableArrayDecayedType - Turns the given type, which may be
2473/// variably-modified, into the corresponding type with all the known
2474/// sizes replaced with [*].
2475QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2476 // Vastly most common case.
2477 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002478
John McCall06549462011-01-18 08:40:38 +00002479 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002480
John McCall06549462011-01-18 08:40:38 +00002481 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002482 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002483 switch (ty->getTypeClass()) {
2484#define TYPE(Class, Base)
2485#define ABSTRACT_TYPE(Class, Base)
2486#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2487#include "clang/AST/TypeNodes.def"
2488 llvm_unreachable("didn't desugar past all non-canonical types?");
2489
2490 // These types should never be variably-modified.
2491 case Type::Builtin:
2492 case Type::Complex:
2493 case Type::Vector:
2494 case Type::ExtVector:
2495 case Type::DependentSizedExtVector:
2496 case Type::ObjCObject:
2497 case Type::ObjCInterface:
2498 case Type::ObjCObjectPointer:
2499 case Type::Record:
2500 case Type::Enum:
2501 case Type::UnresolvedUsing:
2502 case Type::TypeOfExpr:
2503 case Type::TypeOf:
2504 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002505 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002506 case Type::DependentName:
2507 case Type::InjectedClassName:
2508 case Type::TemplateSpecialization:
2509 case Type::DependentTemplateSpecialization:
2510 case Type::TemplateTypeParm:
2511 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002512 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002513 case Type::PackExpansion:
2514 llvm_unreachable("type should never be variably-modified");
2515
2516 // These types can be variably-modified but should never need to
2517 // further decay.
2518 case Type::FunctionNoProto:
2519 case Type::FunctionProto:
2520 case Type::BlockPointer:
2521 case Type::MemberPointer:
2522 return type;
2523
2524 // These types can be variably-modified. All these modifications
2525 // preserve structure except as noted by comments.
2526 // TODO: if we ever care about optimizing VLAs, there are no-op
2527 // optimizations available here.
2528 case Type::Pointer:
2529 result = getPointerType(getVariableArrayDecayedType(
2530 cast<PointerType>(ty)->getPointeeType()));
2531 break;
2532
2533 case Type::LValueReference: {
2534 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2535 result = getLValueReferenceType(
2536 getVariableArrayDecayedType(lv->getPointeeType()),
2537 lv->isSpelledAsLValue());
2538 break;
2539 }
2540
2541 case Type::RValueReference: {
2542 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2543 result = getRValueReferenceType(
2544 getVariableArrayDecayedType(lv->getPointeeType()));
2545 break;
2546 }
2547
Eli Friedman0dfb8892011-10-06 23:00:33 +00002548 case Type::Atomic: {
2549 const AtomicType *at = cast<AtomicType>(ty);
2550 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2551 break;
2552 }
2553
John McCall06549462011-01-18 08:40:38 +00002554 case Type::ConstantArray: {
2555 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2556 result = getConstantArrayType(
2557 getVariableArrayDecayedType(cat->getElementType()),
2558 cat->getSize(),
2559 cat->getSizeModifier(),
2560 cat->getIndexTypeCVRQualifiers());
2561 break;
2562 }
2563
2564 case Type::DependentSizedArray: {
2565 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2566 result = getDependentSizedArrayType(
2567 getVariableArrayDecayedType(dat->getElementType()),
2568 dat->getSizeExpr(),
2569 dat->getSizeModifier(),
2570 dat->getIndexTypeCVRQualifiers(),
2571 dat->getBracketsRange());
2572 break;
2573 }
2574
2575 // Turn incomplete types into [*] types.
2576 case Type::IncompleteArray: {
2577 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2578 result = getVariableArrayType(
2579 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002580 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002581 ArrayType::Normal,
2582 iat->getIndexTypeCVRQualifiers(),
2583 SourceRange());
2584 break;
2585 }
2586
2587 // Turn VLA types into [*] types.
2588 case Type::VariableArray: {
2589 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2590 result = getVariableArrayType(
2591 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002592 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002593 ArrayType::Star,
2594 vat->getIndexTypeCVRQualifiers(),
2595 vat->getBracketsRange());
2596 break;
2597 }
2598 }
2599
2600 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002601 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002602}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002603
Steve Naroffcadebd02007-08-30 18:14:25 +00002604/// getVariableArrayType - Returns a non-unique reference to the type for a
2605/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002606QualType ASTContext::getVariableArrayType(QualType EltTy,
2607 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002608 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002609 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002610 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002611 // Since we don't unique expressions, it isn't possible to unique VLA's
2612 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002613 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002614
John McCall33ddac02011-01-19 10:06:00 +00002615 // Be sure to pull qualifiers off the element type.
2616 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2617 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002618 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002619 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002620 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002621 }
2622
John McCall90d1c2d2009-09-24 23:30:46 +00002623 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002624 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002625
2626 VariableArrayTypes.push_back(New);
2627 Types.push_back(New);
2628 return QualType(New, 0);
2629}
2630
Douglas Gregor4619e432008-12-05 23:32:09 +00002631/// getDependentSizedArrayType - Returns a non-unique reference to
2632/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002633/// type.
John McCall33ddac02011-01-19 10:06:00 +00002634QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2635 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002636 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002637 unsigned elementTypeQuals,
2638 SourceRange brackets) const {
2639 assert((!numElements || numElements->isTypeDependent() ||
2640 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002641 "Size must be type- or value-dependent!");
2642
John McCall33ddac02011-01-19 10:06:00 +00002643 // Dependently-sized array types that do not have a specified number
2644 // of elements will have their sizes deduced from a dependent
2645 // initializer. We do no canonicalization here at all, which is okay
2646 // because they can't be used in most locations.
2647 if (!numElements) {
2648 DependentSizedArrayType *newType
2649 = new (*this, TypeAlignment)
2650 DependentSizedArrayType(*this, elementType, QualType(),
2651 numElements, ASM, elementTypeQuals,
2652 brackets);
2653 Types.push_back(newType);
2654 return QualType(newType, 0);
2655 }
2656
2657 // Otherwise, we actually build a new type every time, but we
2658 // also build a canonical type.
2659
2660 SplitQualType canonElementType = getCanonicalType(elementType).split();
2661
Craig Topper36250ad2014-05-12 05:36:57 +00002662 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002663 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002664 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002665 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002666 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002667
John McCall33ddac02011-01-19 10:06:00 +00002668 // Look for an existing type with these properties.
2669 DependentSizedArrayType *canonTy =
2670 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002671
John McCall33ddac02011-01-19 10:06:00 +00002672 // If we don't have one, build one.
2673 if (!canonTy) {
2674 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002675 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002676 QualType(), numElements, ASM, elementTypeQuals,
2677 brackets);
2678 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2679 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002680 }
2681
John McCall33ddac02011-01-19 10:06:00 +00002682 // Apply qualifiers from the element type to the array.
2683 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002684 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002685
John McCall33ddac02011-01-19 10:06:00 +00002686 // If we didn't need extra canonicalization for the element type,
2687 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002688 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002689 return canon;
2690
2691 // Otherwise, we need to build a type which follows the spelling
2692 // of the element type.
2693 DependentSizedArrayType *sugaredType
2694 = new (*this, TypeAlignment)
2695 DependentSizedArrayType(*this, elementType, canon, numElements,
2696 ASM, elementTypeQuals, brackets);
2697 Types.push_back(sugaredType);
2698 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002699}
2700
John McCall33ddac02011-01-19 10:06:00 +00002701QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002702 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002703 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002704 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002705 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002706
Craig Topper36250ad2014-05-12 05:36:57 +00002707 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002708 if (IncompleteArrayType *iat =
2709 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2710 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002711
2712 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002713 // either, so fill in the canonical type field. We also have to pull
2714 // qualifiers off the element type.
2715 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002716
John McCall33ddac02011-01-19 10:06:00 +00002717 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2718 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002719 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002720 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002721 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002722
2723 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002724 IncompleteArrayType *existing =
2725 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2726 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002727 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002728
John McCall33ddac02011-01-19 10:06:00 +00002729 IncompleteArrayType *newType = new (*this, TypeAlignment)
2730 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002731
John McCall33ddac02011-01-19 10:06:00 +00002732 IncompleteArrayTypes.InsertNode(newType, insertPos);
2733 Types.push_back(newType);
2734 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002735}
2736
Steve Naroff91fcddb2007-07-18 18:00:27 +00002737/// getVectorType - Return the unique reference to a vector type of
2738/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002739QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002740 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002741 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002742
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002743 // Check if we've already instantiated a vector of this type.
2744 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002745 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002746
Craig Topper36250ad2014-05-12 05:36:57 +00002747 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002748 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2749 return QualType(VTP, 0);
2750
2751 // If the element type isn't canonical, this won't be a canonical type either,
2752 // so fill in the canonical type field.
2753 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002754 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002755 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002756
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002757 // Get the new insert position for the node we care about.
2758 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002759 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002760 }
John McCall90d1c2d2009-09-24 23:30:46 +00002761 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002762 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002763 VectorTypes.InsertNode(New, InsertPos);
2764 Types.push_back(New);
2765 return QualType(New, 0);
2766}
2767
Nate Begemance4d7fc2008-04-18 23:10:10 +00002768/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002769/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002770QualType
2771ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002772 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002773
Steve Naroff91fcddb2007-07-18 18:00:27 +00002774 // Check if we've already instantiated a vector of this type.
2775 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002776 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002777 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002778 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002779 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2780 return QualType(VTP, 0);
2781
2782 // If the element type isn't canonical, this won't be a canonical type either,
2783 // so fill in the canonical type field.
2784 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002785 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002786 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002787
Steve Naroff91fcddb2007-07-18 18:00:27 +00002788 // Get the new insert position for the node we care about.
2789 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002790 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002791 }
John McCall90d1c2d2009-09-24 23:30:46 +00002792 ExtVectorType *New = new (*this, TypeAlignment)
2793 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002794 VectorTypes.InsertNode(New, InsertPos);
2795 Types.push_back(New);
2796 return QualType(New, 0);
2797}
2798
Jay Foad39c79802011-01-12 09:06:06 +00002799QualType
2800ASTContext::getDependentSizedExtVectorType(QualType vecType,
2801 Expr *SizeExpr,
2802 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002803 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002804 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002805 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002806
Craig Topper36250ad2014-05-12 05:36:57 +00002807 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002808 DependentSizedExtVectorType *Canon
2809 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2810 DependentSizedExtVectorType *New;
2811 if (Canon) {
2812 // We already have a canonical version of this array type; use it as
2813 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002814 New = new (*this, TypeAlignment)
2815 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2816 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002817 } else {
2818 QualType CanonVecTy = getCanonicalType(vecType);
2819 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002820 New = new (*this, TypeAlignment)
2821 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2822 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002823
2824 DependentSizedExtVectorType *CanonCheck
2825 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2826 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2827 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002828 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2829 } else {
2830 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2831 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002832 New = new (*this, TypeAlignment)
2833 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002834 }
2835 }
Mike Stump11289f42009-09-09 15:08:12 +00002836
Douglas Gregor758a8692009-06-17 21:51:59 +00002837 Types.push_back(New);
2838 return QualType(New, 0);
2839}
2840
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002841/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002842///
Jay Foad39c79802011-01-12 09:06:06 +00002843QualType
2844ASTContext::getFunctionNoProtoType(QualType ResultTy,
2845 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002846 const CallingConv CallConv = Info.getCC();
2847
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002848 // Unique functions, to guarantee there is only one function of a particular
2849 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002850 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002851 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002852
Craig Topper36250ad2014-05-12 05:36:57 +00002853 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002854 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002855 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002856 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002857
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002858 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002859 if (!ResultTy.isCanonical()) {
2860 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002861
Chris Lattner47955de2007-01-27 08:37:20 +00002862 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002863 FunctionNoProtoType *NewIP =
2864 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002865 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002866 }
Mike Stump11289f42009-09-09 15:08:12 +00002867
Roman Divacky65b88cd2011-03-01 17:40:53 +00002868 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002869 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002870 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002871 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002872 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002873 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002874}
2875
Douglas Gregorcd780372013-01-17 23:36:45 +00002876/// \brief Determine whether \p T is canonical as the result type of a function.
2877static bool isCanonicalResultType(QualType T) {
2878 return T.isCanonical() &&
2879 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2880 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2881}
2882
Jay Foad39c79802011-01-12 09:06:06 +00002883QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002884ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002885 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002886 size_t NumArgs = ArgArray.size();
2887
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002888 // Unique functions, to guarantee there is only one function of a particular
2889 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002890 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002891 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2892 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002893
Craig Topper36250ad2014-05-12 05:36:57 +00002894 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002895 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002896 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002897 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002898
2899 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002900 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002901 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002902 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002903 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002904 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002905 isCanonical = false;
2906
2907 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002908 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002909 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002910 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002911 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002912 CanonicalArgs.reserve(NumArgs);
2913 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002914 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002915
John McCalldb40c7f2010-12-14 08:05:40 +00002916 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002917 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002918 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002919
Douglas Gregorcd780372013-01-17 23:36:45 +00002920 // Result types do not have ARC lifetime qualifiers.
2921 QualType CanResultTy = getCanonicalType(ResultTy);
2922 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2923 Qualifiers Qs = CanResultTy.getQualifiers();
2924 Qs.removeObjCLifetime();
2925 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2926 }
2927
Jordan Rose5c382722013-03-08 21:51:21 +00002928 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002929
Chris Lattnerfd4de792007-01-27 01:15:32 +00002930 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002931 FunctionProtoType *NewIP =
2932 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002933 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002934 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002935
John McCall31168b02011-06-15 23:02:42 +00002936 // FunctionProtoType objects are allocated with extra bytes after
2937 // them for three variable size arrays at the end:
2938 // - parameter types
2939 // - exception types
2940 // - consumed-arguments flags
2941 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002942 // expression, or information used to resolve the exception
2943 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002944 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002945 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00002946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2947 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2948 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002949 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00002950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002951 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00002952 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002953 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002954 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002955 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002956 Size += NumArgs * sizeof(bool);
2957
John McCalldb40c7f2010-12-14 08:05:40 +00002958 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002959 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002960 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002961 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002962 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002963 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002964}
Chris Lattneref51c202006-11-10 07:17:23 +00002965
John McCalle78aac42010-03-10 03:28:59 +00002966#ifndef NDEBUG
2967static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2968 if (!isa<CXXRecordDecl>(D)) return false;
2969 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2970 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2971 return true;
2972 if (RD->getDescribedClassTemplate() &&
2973 !isa<ClassTemplateSpecializationDecl>(RD))
2974 return true;
2975 return false;
2976}
2977#endif
2978
2979/// getInjectedClassNameType - Return the unique reference to the
2980/// injected class name type for the specified templated declaration.
2981QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002982 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002983 assert(NeedsInjectedClassNameType(Decl));
2984 if (Decl->TypeForDecl) {
2985 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002986 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002987 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2988 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2989 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2990 } else {
John McCall424cec92011-01-19 06:33:43 +00002991 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002992 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002993 Decl->TypeForDecl = newType;
2994 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002995 }
2996 return QualType(Decl->TypeForDecl, 0);
2997}
2998
Douglas Gregor83a586e2008-04-13 21:07:44 +00002999/// getTypeDeclType - Return the unique reference to the type for the
3000/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003001QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003002 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003003 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003004
Richard Smithdda56e42011-04-15 14:24:37 +00003005 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003006 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003007
John McCall96f0b5f2010-03-10 06:48:02 +00003008 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3009 "Template type parameter types are always available.");
3010
John McCall81e38502010-02-16 03:57:14 +00003011 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003012 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003013 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003014 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003015 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003016 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003017 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003018 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003019 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003020 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3021 Decl->TypeForDecl = newType;
3022 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003023 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003024 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003025
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003026 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003027}
3028
Chris Lattner32d920b2007-01-26 02:01:53 +00003029/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003030/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003031QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003032ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3033 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003034 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003035
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003036 if (Canonical.isNull())
3037 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003038 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003039 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003040 Decl->TypeForDecl = newType;
3041 Types.push_back(newType);
3042 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003043}
3044
Jay Foad39c79802011-01-12 09:06:06 +00003045QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003046 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3047
Douglas Gregorec9fd132012-01-14 16:38:05 +00003048 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003049 if (PrevDecl->TypeForDecl)
3050 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3051
John McCall424cec92011-01-19 06:33:43 +00003052 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3053 Decl->TypeForDecl = newType;
3054 Types.push_back(newType);
3055 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003056}
3057
Jay Foad39c79802011-01-12 09:06:06 +00003058QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003059 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3060
Douglas Gregorec9fd132012-01-14 16:38:05 +00003061 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003062 if (PrevDecl->TypeForDecl)
3063 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3064
John McCall424cec92011-01-19 06:33:43 +00003065 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3066 Decl->TypeForDecl = newType;
3067 Types.push_back(newType);
3068 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003069}
3070
John McCall81904512011-01-06 01:58:22 +00003071QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3072 QualType modifiedType,
3073 QualType equivalentType) {
3074 llvm::FoldingSetNodeID id;
3075 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3076
Craig Topper36250ad2014-05-12 05:36:57 +00003077 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003078 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3079 if (type) return QualType(type, 0);
3080
3081 QualType canon = getCanonicalType(equivalentType);
3082 type = new (*this, TypeAlignment)
3083 AttributedType(canon, attrKind, modifiedType, equivalentType);
3084
3085 Types.push_back(type);
3086 AttributedTypes.InsertNode(type, insertPos);
3087
3088 return QualType(type, 0);
3089}
3090
3091
John McCallcebee162009-10-18 09:09:24 +00003092/// \brief Retrieve a substitution-result type.
3093QualType
3094ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003095 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003096 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003097 && "replacement types must always be canonical");
3098
3099 llvm::FoldingSetNodeID ID;
3100 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003101 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003102 SubstTemplateTypeParmType *SubstParm
3103 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3104
3105 if (!SubstParm) {
3106 SubstParm = new (*this, TypeAlignment)
3107 SubstTemplateTypeParmType(Parm, Replacement);
3108 Types.push_back(SubstParm);
3109 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3110 }
3111
3112 return QualType(SubstParm, 0);
3113}
3114
Douglas Gregorada4b792011-01-14 02:55:32 +00003115/// \brief Retrieve a
3116QualType ASTContext::getSubstTemplateTypeParmPackType(
3117 const TemplateTypeParmType *Parm,
3118 const TemplateArgument &ArgPack) {
3119#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003120 for (const auto &P : ArgPack.pack_elements()) {
3121 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3122 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003123 }
3124#endif
3125
3126 llvm::FoldingSetNodeID ID;
3127 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003128 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003129 if (SubstTemplateTypeParmPackType *SubstParm
3130 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3131 return QualType(SubstParm, 0);
3132
3133 QualType Canon;
3134 if (!Parm->isCanonicalUnqualified()) {
3135 Canon = getCanonicalType(QualType(Parm, 0));
3136 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3137 ArgPack);
3138 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3139 }
3140
3141 SubstTemplateTypeParmPackType *SubstParm
3142 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3143 ArgPack);
3144 Types.push_back(SubstParm);
3145 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3146 return QualType(SubstParm, 0);
3147}
3148
Douglas Gregoreff93e02009-02-05 23:33:38 +00003149/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003150/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003151/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003152QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003153 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003154 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003155 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003156 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003157 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003158 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003159 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3160
3161 if (TypeParm)
3162 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003163
Chandler Carruth08836322011-05-01 00:51:33 +00003164 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003165 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003166 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003167
3168 TemplateTypeParmType *TypeCheck
3169 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3170 assert(!TypeCheck && "Template type parameter canonical type broken");
3171 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003172 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003173 TypeParm = new (*this, TypeAlignment)
3174 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003175
3176 Types.push_back(TypeParm);
3177 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3178
3179 return QualType(TypeParm, 0);
3180}
3181
John McCalle78aac42010-03-10 03:28:59 +00003182TypeSourceInfo *
3183ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3184 SourceLocation NameLoc,
3185 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003186 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003187 assert(!Name.getAsDependentTemplateName() &&
3188 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003189 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003190
3191 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003192 TemplateSpecializationTypeLoc TL =
3193 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003194 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003195 TL.setTemplateNameLoc(NameLoc);
3196 TL.setLAngleLoc(Args.getLAngleLoc());
3197 TL.setRAngleLoc(Args.getRAngleLoc());
3198 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3199 TL.setArgLocInfo(i, Args[i].getLocInfo());
3200 return DI;
3201}
3202
Mike Stump11289f42009-09-09 15:08:12 +00003203QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003204ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003205 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003206 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003207 assert(!Template.getAsDependentTemplateName() &&
3208 "No dependent template names here!");
3209
John McCall6b51f282009-11-23 01:53:49 +00003210 unsigned NumArgs = Args.size();
3211
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003212 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003213 ArgVec.reserve(NumArgs);
3214 for (unsigned i = 0; i != NumArgs; ++i)
3215 ArgVec.push_back(Args[i].getArgument());
3216
John McCall2408e322010-04-27 00:57:59 +00003217 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003218 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003219}
3220
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003221#ifndef NDEBUG
3222static bool hasAnyPackExpansions(const TemplateArgument *Args,
3223 unsigned NumArgs) {
3224 for (unsigned I = 0; I != NumArgs; ++I)
3225 if (Args[I].isPackExpansion())
3226 return true;
3227
3228 return true;
3229}
3230#endif
3231
John McCall0ad16662009-10-29 08:12:44 +00003232QualType
3233ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003234 const TemplateArgument *Args,
3235 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003236 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003237 assert(!Template.getAsDependentTemplateName() &&
3238 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003239 // Look through qualified template names.
3240 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3241 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003242
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003243 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003244 Template.getAsTemplateDecl() &&
3245 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003246 QualType CanonType;
3247 if (!Underlying.isNull())
3248 CanonType = getCanonicalType(Underlying);
3249 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003250 // We can get here with an alias template when the specialization contains
3251 // a pack expansion that does not match up with a parameter pack.
3252 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3253 "Caller must compute aliased type");
3254 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003255 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3256 NumArgs);
3257 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003258
Douglas Gregora8e02e72009-07-28 23:00:59 +00003259 // Allocate the (non-canonical) template specialization type, but don't
3260 // try to unique it: these types typically have location information that
3261 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003262 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3263 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003264 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003265 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003266 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003267 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3268 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003269
Douglas Gregor8bf42052009-02-09 18:46:07 +00003270 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003271 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003272}
3273
Mike Stump11289f42009-09-09 15:08:12 +00003274QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003275ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3276 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003277 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003278 assert(!Template.getAsDependentTemplateName() &&
3279 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003280
Douglas Gregore29139c2011-03-03 17:04:51 +00003281 // Look through qualified template names.
3282 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3283 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003284
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003285 // Build the canonical template specialization type.
3286 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003287 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003288 CanonArgs.reserve(NumArgs);
3289 for (unsigned I = 0; I != NumArgs; ++I)
3290 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3291
3292 // Determine whether this canonical template specialization type already
3293 // exists.
3294 llvm::FoldingSetNodeID ID;
3295 TemplateSpecializationType::Profile(ID, CanonTemplate,
3296 CanonArgs.data(), NumArgs, *this);
3297
Craig Topper36250ad2014-05-12 05:36:57 +00003298 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003299 TemplateSpecializationType *Spec
3300 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3301
3302 if (!Spec) {
3303 // Allocate a new canonical template specialization type.
3304 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3305 sizeof(TemplateArgument) * NumArgs),
3306 TypeAlignment);
3307 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3308 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003309 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003310 Types.push_back(Spec);
3311 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3312 }
3313
3314 assert(Spec->isDependentType() &&
3315 "Non-dependent template-id type must have a canonical type");
3316 return QualType(Spec, 0);
3317}
3318
3319QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003320ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3321 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003322 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003323 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003324 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003325
Craig Topper36250ad2014-05-12 05:36:57 +00003326 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003327 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003328 if (T)
3329 return QualType(T, 0);
3330
Douglas Gregorc42075a2010-02-04 18:10:26 +00003331 QualType Canon = NamedType;
3332 if (!Canon.isCanonical()) {
3333 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003334 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3335 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003336 (void)CheckT;
3337 }
3338
Abramo Bagnara6150c882010-05-11 21:36:43 +00003339 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003340 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003341 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003342 return QualType(T, 0);
3343}
3344
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003345QualType
Jay Foad39c79802011-01-12 09:06:06 +00003346ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003347 llvm::FoldingSetNodeID ID;
3348 ParenType::Profile(ID, InnerType);
3349
Craig Topper36250ad2014-05-12 05:36:57 +00003350 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003351 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3352 if (T)
3353 return QualType(T, 0);
3354
3355 QualType Canon = InnerType;
3356 if (!Canon.isCanonical()) {
3357 Canon = getCanonicalType(InnerType);
3358 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3359 assert(!CheckT && "Paren canonical type broken");
3360 (void)CheckT;
3361 }
3362
3363 T = new (*this) ParenType(InnerType, Canon);
3364 Types.push_back(T);
3365 ParenTypes.InsertNode(T, InsertPos);
3366 return QualType(T, 0);
3367}
3368
Douglas Gregor02085352010-03-31 20:19:30 +00003369QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3370 NestedNameSpecifier *NNS,
3371 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003372 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003373 if (Canon.isNull()) {
3374 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003375 ElaboratedTypeKeyword CanonKeyword = Keyword;
3376 if (Keyword == ETK_None)
3377 CanonKeyword = ETK_Typename;
3378
3379 if (CanonNNS != NNS || CanonKeyword != Keyword)
3380 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003381 }
3382
3383 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003384 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003385
Craig Topper36250ad2014-05-12 05:36:57 +00003386 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003387 DependentNameType *T
3388 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003389 if (T)
3390 return QualType(T, 0);
3391
Douglas Gregor02085352010-03-31 20:19:30 +00003392 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003393 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003394 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003395 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003396}
3397
Mike Stump11289f42009-09-09 15:08:12 +00003398QualType
John McCallc392f372010-06-11 00:33:02 +00003399ASTContext::getDependentTemplateSpecializationType(
3400 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003401 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003402 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003403 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003404 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003405 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003406 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3407 ArgCopy.push_back(Args[I].getArgument());
3408 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3409 ArgCopy.size(),
3410 ArgCopy.data());
3411}
3412
3413QualType
3414ASTContext::getDependentTemplateSpecializationType(
3415 ElaboratedTypeKeyword Keyword,
3416 NestedNameSpecifier *NNS,
3417 const IdentifierInfo *Name,
3418 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003419 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003420 assert((!NNS || NNS->isDependent()) &&
3421 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003422
Douglas Gregorc42075a2010-02-04 18:10:26 +00003423 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003424 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3425 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003426
Craig Topper36250ad2014-05-12 05:36:57 +00003427 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003428 DependentTemplateSpecializationType *T
3429 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003430 if (T)
3431 return QualType(T, 0);
3432
John McCallc392f372010-06-11 00:33:02 +00003433 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003434
John McCallc392f372010-06-11 00:33:02 +00003435 ElaboratedTypeKeyword CanonKeyword = Keyword;
3436 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3437
3438 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003439 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003440 for (unsigned I = 0; I != NumArgs; ++I) {
3441 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3442 if (!CanonArgs[I].structurallyEquals(Args[I]))
3443 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003444 }
3445
John McCallc392f372010-06-11 00:33:02 +00003446 QualType Canon;
3447 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3448 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3449 Name, NumArgs,
3450 CanonArgs.data());
3451
3452 // Find the insert position again.
3453 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3454 }
3455
3456 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3457 sizeof(TemplateArgument) * NumArgs),
3458 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003459 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003460 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003461 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003462 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003463 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003464}
3465
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003466QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003467 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003468 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003469 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003470
3471 assert(Pattern->containsUnexpandedParameterPack() &&
3472 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003473 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003474 PackExpansionType *T
3475 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3476 if (T)
3477 return QualType(T, 0);
3478
3479 QualType Canon;
3480 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003481 Canon = getCanonicalType(Pattern);
3482 // The canonical type might not contain an unexpanded parameter pack, if it
3483 // contains an alias template specialization which ignores one of its
3484 // parameters.
3485 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003486 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003487
Richard Smith68eea502012-07-16 00:20:35 +00003488 // Find the insert position again, in case we inserted an element into
3489 // PackExpansionTypes and invalidated our insert position.
3490 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3491 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003492 }
3493
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003494 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003495 Types.push_back(T);
3496 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003497 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003498}
3499
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003500/// CmpProtocolNames - Comparison predicate for sorting protocols
3501/// alphabetically.
3502static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3503 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003504 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003505}
3506
John McCall8b07ec22010-05-15 11:32:37 +00003507static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003508 unsigned NumProtocols) {
3509 if (NumProtocols == 0) return true;
3510
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003511 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3512 return false;
3513
John McCallfc93cf92009-10-22 22:37:11 +00003514 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003515 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3516 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003517 return false;
3518 return true;
3519}
3520
3521static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003522 unsigned &NumProtocols) {
3523 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003524
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003525 // Sort protocols, keyed by name.
3526 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3527
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003528 // Canonicalize.
3529 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3530 Protocols[I] = Protocols[I]->getCanonicalDecl();
3531
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003532 // Remove duplicates.
3533 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3534 NumProtocols = ProtocolsEnd-Protocols;
3535}
3536
John McCall8b07ec22010-05-15 11:32:37 +00003537QualType ASTContext::getObjCObjectType(QualType BaseType,
3538 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003539 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003540 // If the base type is an interface and there aren't any protocols
3541 // to add, then the interface type will do just fine.
3542 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3543 return BaseType;
3544
3545 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003546 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003547 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003548 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003549 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3550 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003551
John McCall8b07ec22010-05-15 11:32:37 +00003552 // Build the canonical type, which has the canonical base type and
3553 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003554 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003555 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3556 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3557 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003558 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003559 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003560 unsigned UniqueCount = NumProtocols;
3561
John McCallfc93cf92009-10-22 22:37:11 +00003562 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003563 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3564 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003565 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003566 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3567 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003568 }
3569
3570 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003571 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3572 }
3573
3574 unsigned Size = sizeof(ObjCObjectTypeImpl);
3575 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3576 void *Mem = Allocate(Size, TypeAlignment);
3577 ObjCObjectTypeImpl *T =
3578 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3579
3580 Types.push_back(T);
3581 ObjCObjectTypes.InsertNode(T, InsertPos);
3582 return QualType(T, 0);
3583}
3584
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003585/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3586/// protocol list adopt all protocols in QT's qualified-id protocol
3587/// list.
3588bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3589 ObjCInterfaceDecl *IC) {
3590 if (!QT->isObjCQualifiedIdType())
3591 return false;
3592
3593 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3594 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003595 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003596 if (!IC->ClassImplementsProtocol(Proto, false))
3597 return false;
3598 }
3599 return true;
3600 }
3601 return false;
3602}
3603
3604/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3605/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3606/// of protocols.
3607bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3608 ObjCInterfaceDecl *IDecl) {
3609 if (!QT->isObjCQualifiedIdType())
3610 return false;
3611 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3612 if (!OPT)
3613 return false;
3614 if (!IDecl->hasDefinition())
3615 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003616 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3617 CollectInheritedProtocols(IDecl, InheritedProtocols);
3618 if (InheritedProtocols.empty())
3619 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003620 // Check that if every protocol in list of id<plist> conforms to a protcol
3621 // of IDecl's, then bridge casting is ok.
3622 bool Conforms = false;
3623 for (auto *Proto : OPT->quals()) {
3624 Conforms = false;
3625 for (auto *PI : InheritedProtocols) {
3626 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3627 Conforms = true;
3628 break;
3629 }
3630 }
3631 if (!Conforms)
3632 break;
3633 }
3634 if (Conforms)
3635 return true;
3636
Aaron Ballman83731462014-03-17 16:14:00 +00003637 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003638 // If both the right and left sides have qualifiers.
3639 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003640 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003641 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003642 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003643 break;
3644 }
3645 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003646 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003647 }
3648 return true;
3649}
3650
John McCall8b07ec22010-05-15 11:32:37 +00003651/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3652/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003653QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003654 llvm::FoldingSetNodeID ID;
3655 ObjCObjectPointerType::Profile(ID, ObjectT);
3656
Craig Topper36250ad2014-05-12 05:36:57 +00003657 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003658 if (ObjCObjectPointerType *QT =
3659 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3660 return QualType(QT, 0);
3661
3662 // Find the canonical object type.
3663 QualType Canonical;
3664 if (!ObjectT.isCanonical()) {
3665 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3666
3667 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003668 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3669 }
3670
Douglas Gregorf85bee62010-02-08 22:59:26 +00003671 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003672 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3673 ObjCObjectPointerType *QType =
3674 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003675
Steve Narofffb4330f2009-06-17 22:40:22 +00003676 Types.push_back(QType);
3677 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003678 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003679}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003680
Douglas Gregor1c283312010-08-11 12:19:30 +00003681/// getObjCInterfaceType - Return the unique reference to the type for the
3682/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003683QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3684 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003685 if (Decl->TypeForDecl)
3686 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003688 if (PrevDecl) {
3689 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3690 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3691 return QualType(PrevDecl->TypeForDecl, 0);
3692 }
3693
Douglas Gregor7671e532011-12-16 16:34:57 +00003694 // Prefer the definition, if there is one.
3695 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3696 Decl = Def;
3697
Douglas Gregor1c283312010-08-11 12:19:30 +00003698 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3699 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3700 Decl->TypeForDecl = T;
3701 Types.push_back(T);
3702 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003703}
3704
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003705/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3706/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003707/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003708/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003709/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003710QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003711 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003712 if (tofExpr->isTypeDependent()) {
3713 llvm::FoldingSetNodeID ID;
3714 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003715
Craig Topper36250ad2014-05-12 05:36:57 +00003716 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003717 DependentTypeOfExprType *Canon
3718 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3719 if (Canon) {
3720 // We already have a "canonical" version of an identical, dependent
3721 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003722 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003723 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003724 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003725 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003726 Canon
3727 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003728 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3729 toe = Canon;
3730 }
3731 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003732 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003733 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003734 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003735 Types.push_back(toe);
3736 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003737}
3738
Steve Naroffa773cd52007-08-01 18:02:17 +00003739/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003740/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003741/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003742/// an issue. This doesn't affect the type checker, since it operates
3743/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003744QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003745 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003746 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003747 Types.push_back(tot);
3748 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003749}
3750
Anders Carlssonad6bd352009-06-24 21:24:56 +00003751
Richard Smith8eb1d322014-06-05 20:13:13 +00003752/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3753/// nodes. This would never be helpful, since each such type has its own
3754/// expression, and would not give a significant memory saving, since there
3755/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003756QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003757 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003758
3759 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003760 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003761 // unique dependent type. Two such decltype-specifiers refer to the same
3762 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003763 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003764 llvm::FoldingSetNodeID ID;
3765 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003766
Craig Topper36250ad2014-05-12 05:36:57 +00003767 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003768 DependentDecltypeType *Canon
3769 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003770 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003771 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003772 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003773 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003774 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003775 dt = new (*this, TypeAlignment)
3776 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003777 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003778 dt = new (*this, TypeAlignment)
3779 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003780 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003781 Types.push_back(dt);
3782 return QualType(dt, 0);
3783}
3784
Alexis Hunte852b102011-05-24 22:41:36 +00003785/// getUnaryTransformationType - We don't unique these, since the memory
3786/// savings are minimal and these are rare.
3787QualType ASTContext::getUnaryTransformType(QualType BaseType,
3788 QualType UnderlyingType,
3789 UnaryTransformType::UTTKind Kind)
3790 const {
3791 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003792 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3793 Kind,
3794 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003795 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003796 Types.push_back(Ty);
3797 return QualType(Ty, 0);
3798}
3799
Richard Smith2a7d4812013-05-04 07:00:32 +00003800/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3801/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3802/// canonical deduced-but-dependent 'auto' type.
3803QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003804 bool IsDependent) const {
3805 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003806 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003807
Richard Smith2a7d4812013-05-04 07:00:32 +00003808 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003809 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003810 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003811 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003812 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3813 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003814
Richard Smith74aeef52013-04-26 16:15:35 +00003815 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003816 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003817 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003818 Types.push_back(AT);
3819 if (InsertPos)
3820 AutoTypes.InsertNode(AT, InsertPos);
3821 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003822}
3823
Eli Friedman0dfb8892011-10-06 23:00:33 +00003824/// getAtomicType - Return the uniqued reference to the atomic type for
3825/// the given value type.
3826QualType ASTContext::getAtomicType(QualType T) const {
3827 // Unique pointers, to guarantee there is only one pointer of a particular
3828 // structure.
3829 llvm::FoldingSetNodeID ID;
3830 AtomicType::Profile(ID, T);
3831
Craig Topper36250ad2014-05-12 05:36:57 +00003832 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003833 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3834 return QualType(AT, 0);
3835
3836 // If the atomic value type isn't canonical, this won't be a canonical type
3837 // either, so fill in the canonical type field.
3838 QualType Canonical;
3839 if (!T.isCanonical()) {
3840 Canonical = getAtomicType(getCanonicalType(T));
3841
3842 // Get the new insert position for the node we care about.
3843 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003844 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003845 }
3846 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3847 Types.push_back(New);
3848 AtomicTypes.InsertNode(New, InsertPos);
3849 return QualType(New, 0);
3850}
3851
Richard Smith02e85f32011-04-14 22:09:26 +00003852/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3853QualType ASTContext::getAutoDeductType() const {
3854 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003855 AutoDeductTy = QualType(
3856 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003857 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003858 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003859 return AutoDeductTy;
3860}
3861
3862/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3863QualType ASTContext::getAutoRRefDeductType() const {
3864 if (AutoRRefDeductTy.isNull())
3865 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3866 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3867 return AutoRRefDeductTy;
3868}
3869
Chris Lattnerfb072462007-01-23 05:45:31 +00003870/// getTagDeclType - Return the unique reference to the type for the
3871/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003872QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003873 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003874 // FIXME: What is the design on getTagDeclType when it requires casting
3875 // away const? mutable?
3876 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003877}
3878
Mike Stump11289f42009-09-09 15:08:12 +00003879/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3880/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3881/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003882CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003883 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003884}
Chris Lattnerfb072462007-01-23 05:45:31 +00003885
Hans Wennborg27541db2011-10-27 08:29:09 +00003886/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3887CanQualType ASTContext::getIntMaxType() const {
3888 return getFromTargetType(Target->getIntMaxType());
3889}
3890
3891/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3892CanQualType ASTContext::getUIntMaxType() const {
3893 return getFromTargetType(Target->getUIntMaxType());
3894}
3895
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003896/// getSignedWCharType - Return the type of "signed wchar_t".
3897/// Used when in C++, as a GCC extension.
3898QualType ASTContext::getSignedWCharType() const {
3899 // FIXME: derive from "Target" ?
3900 return WCharTy;
3901}
3902
3903/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3904/// Used when in C++, as a GCC extension.
3905QualType ASTContext::getUnsignedWCharType() const {
3906 // FIXME: derive from "Target" ?
3907 return UnsignedIntTy;
3908}
3909
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003910QualType ASTContext::getIntPtrType() const {
3911 return getFromTargetType(Target->getIntPtrType());
3912}
3913
3914QualType ASTContext::getUIntPtrType() const {
3915 return getCorrespondingUnsignedType(getIntPtrType());
3916}
3917
Hans Wennborg27541db2011-10-27 08:29:09 +00003918/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003919/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3920QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003921 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003922}
3923
Eli Friedman4e91899e2012-11-27 02:58:24 +00003924/// \brief Return the unique type for "pid_t" defined in
3925/// <sys/types.h>. We need this to compute the correct type for vfork().
3926QualType ASTContext::getProcessIDType() const {
3927 return getFromTargetType(Target->getProcessIDType());
3928}
3929
Chris Lattnera21ad802008-04-02 05:18:44 +00003930//===----------------------------------------------------------------------===//
3931// Type Operators
3932//===----------------------------------------------------------------------===//
3933
Jay Foad39c79802011-01-12 09:06:06 +00003934CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003935 // Push qualifiers into arrays, and then discard any remaining
3936 // qualifiers.
3937 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003938 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003939 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003940 QualType Result;
3941 if (isa<ArrayType>(Ty)) {
3942 Result = getArrayDecayedType(QualType(Ty,0));
3943 } else if (isa<FunctionType>(Ty)) {
3944 Result = getPointerType(QualType(Ty, 0));
3945 } else {
3946 Result = QualType(Ty, 0);
3947 }
3948
3949 return CanQualType::CreateUnsafe(Result);
3950}
3951
John McCall6c9dd522011-01-18 07:41:22 +00003952QualType ASTContext::getUnqualifiedArrayType(QualType type,
3953 Qualifiers &quals) {
3954 SplitQualType splitType = type.getSplitUnqualifiedType();
3955
3956 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3957 // the unqualified desugared type and then drops it on the floor.
3958 // We then have to strip that sugar back off with
3959 // getUnqualifiedDesugaredType(), which is silly.
3960 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003961 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003962
3963 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003964 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003965 quals = splitType.Quals;
3966 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003967 }
3968
John McCall6c9dd522011-01-18 07:41:22 +00003969 // Otherwise, recurse on the array's element type.
3970 QualType elementType = AT->getElementType();
3971 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3972
3973 // If that didn't change the element type, AT has no qualifiers, so we
3974 // can just use the results in splitType.
3975 if (elementType == unqualElementType) {
3976 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003977 quals = splitType.Quals;
3978 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003979 }
3980
3981 // Otherwise, add in the qualifiers from the outermost type, then
3982 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003983 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003984
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003985 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003986 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003987 CAT->getSizeModifier(), 0);
3988 }
3989
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003990 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003991 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003992 }
3993
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003994 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003995 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003996 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003997 VAT->getSizeModifier(),
3998 VAT->getIndexTypeCVRQualifiers(),
3999 VAT->getBracketsRange());
4000 }
4001
4002 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004003 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004004 DSAT->getSizeModifier(), 0,
4005 SourceRange());
4006}
4007
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004008/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4009/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4010/// they point to and return true. If T1 and T2 aren't pointer types
4011/// or pointer-to-member types, or if they are not similar at this
4012/// level, returns false and leaves T1 and T2 unchanged. Top-level
4013/// qualifiers on T1 and T2 are ignored. This function will typically
4014/// be called in a loop that successively "unwraps" pointer and
4015/// pointer-to-member types to compare them at each level.
4016bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4017 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4018 *T2PtrType = T2->getAs<PointerType>();
4019 if (T1PtrType && T2PtrType) {
4020 T1 = T1PtrType->getPointeeType();
4021 T2 = T2PtrType->getPointeeType();
4022 return true;
4023 }
4024
4025 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4026 *T2MPType = T2->getAs<MemberPointerType>();
4027 if (T1MPType && T2MPType &&
4028 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4029 QualType(T2MPType->getClass(), 0))) {
4030 T1 = T1MPType->getPointeeType();
4031 T2 = T2MPType->getPointeeType();
4032 return true;
4033 }
4034
David Blaikiebbafb8a2012-03-11 07:00:24 +00004035 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004036 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4037 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4038 if (T1OPType && T2OPType) {
4039 T1 = T1OPType->getPointeeType();
4040 T2 = T2OPType->getPointeeType();
4041 return true;
4042 }
4043 }
4044
4045 // FIXME: Block pointers, too?
4046
4047 return false;
4048}
4049
Jay Foad39c79802011-01-12 09:06:06 +00004050DeclarationNameInfo
4051ASTContext::getNameForTemplate(TemplateName Name,
4052 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004053 switch (Name.getKind()) {
4054 case TemplateName::QualifiedTemplate:
4055 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004056 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004057 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4058 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004059
John McCalld9dfe3a2011-06-30 08:33:18 +00004060 case TemplateName::OverloadedTemplate: {
4061 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4062 // DNInfo work in progress: CHECKME: what about DNLoc?
4063 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4064 }
4065
4066 case TemplateName::DependentTemplate: {
4067 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004068 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004069 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004070 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4071 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004072 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004073 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4074 // DNInfo work in progress: FIXME: source locations?
4075 DeclarationNameLoc DNLoc;
4076 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4077 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4078 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004079 }
4080 }
4081
John McCalld9dfe3a2011-06-30 08:33:18 +00004082 case TemplateName::SubstTemplateTemplateParm: {
4083 SubstTemplateTemplateParmStorage *subst
4084 = Name.getAsSubstTemplateTemplateParm();
4085 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4086 NameLoc);
4087 }
4088
4089 case TemplateName::SubstTemplateTemplateParmPack: {
4090 SubstTemplateTemplateParmPackStorage *subst
4091 = Name.getAsSubstTemplateTemplateParmPack();
4092 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4093 NameLoc);
4094 }
4095 }
4096
4097 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004098}
4099
Jay Foad39c79802011-01-12 09:06:06 +00004100TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004101 switch (Name.getKind()) {
4102 case TemplateName::QualifiedTemplate:
4103 case TemplateName::Template: {
4104 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004105 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004106 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004107 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4108
4109 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004110 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004111 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004112
John McCalld9dfe3a2011-06-30 08:33:18 +00004113 case TemplateName::OverloadedTemplate:
4114 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004115
John McCalld9dfe3a2011-06-30 08:33:18 +00004116 case TemplateName::DependentTemplate: {
4117 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4118 assert(DTN && "Non-dependent template names must refer to template decls.");
4119 return DTN->CanonicalTemplateName;
4120 }
4121
4122 case TemplateName::SubstTemplateTemplateParm: {
4123 SubstTemplateTemplateParmStorage *subst
4124 = Name.getAsSubstTemplateTemplateParm();
4125 return getCanonicalTemplateName(subst->getReplacement());
4126 }
4127
4128 case TemplateName::SubstTemplateTemplateParmPack: {
4129 SubstTemplateTemplateParmPackStorage *subst
4130 = Name.getAsSubstTemplateTemplateParmPack();
4131 TemplateTemplateParmDecl *canonParameter
4132 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4133 TemplateArgument canonArgPack
4134 = getCanonicalTemplateArgument(subst->getArgumentPack());
4135 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4136 }
4137 }
4138
4139 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004140}
4141
Douglas Gregoradee3e32009-11-11 23:06:43 +00004142bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4143 X = getCanonicalTemplateName(X);
4144 Y = getCanonicalTemplateName(Y);
4145 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4146}
4147
Mike Stump11289f42009-09-09 15:08:12 +00004148TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004149ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004150 switch (Arg.getKind()) {
4151 case TemplateArgument::Null:
4152 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004153
Douglas Gregora8e02e72009-07-28 23:00:59 +00004154 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004155 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004156
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004157 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004158 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004159 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004160 }
Mike Stump11289f42009-09-09 15:08:12 +00004161
Eli Friedmanb826a002012-09-26 02:36:12 +00004162 case TemplateArgument::NullPtr:
4163 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4164 /*isNullPtr*/true);
4165
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004166 case TemplateArgument::Template:
4167 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004168
4169 case TemplateArgument::TemplateExpansion:
4170 return TemplateArgument(getCanonicalTemplateName(
4171 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004172 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004173
Douglas Gregora8e02e72009-07-28 23:00:59 +00004174 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004175 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004176
Douglas Gregora8e02e72009-07-28 23:00:59 +00004177 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004178 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004179
Douglas Gregora8e02e72009-07-28 23:00:59 +00004180 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004181 if (Arg.pack_size() == 0)
4182 return Arg;
4183
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004184 TemplateArgument *CanonArgs
4185 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004186 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004187 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004188 AEnd = Arg.pack_end();
4189 A != AEnd; (void)++A, ++Idx)
4190 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004191
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004192 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004193 }
4194 }
4195
4196 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004197 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004198}
4199
Douglas Gregor333489b2009-03-27 23:10:48 +00004200NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004201ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004202 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004203 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004204
4205 switch (NNS->getKind()) {
4206 case NestedNameSpecifier::Identifier:
4207 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004208 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004209 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4210 NNS->getAsIdentifier());
4211
4212 case NestedNameSpecifier::Namespace:
4213 // A namespace is canonical; build a nested-name-specifier with
4214 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004215 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004216 NNS->getAsNamespace()->getOriginalNamespace());
4217
4218 case NestedNameSpecifier::NamespaceAlias:
4219 // A namespace is canonical; build a nested-name-specifier with
4220 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004221 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004222 NNS->getAsNamespaceAlias()->getNamespace()
4223 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004224
4225 case NestedNameSpecifier::TypeSpec:
4226 case NestedNameSpecifier::TypeSpecWithTemplate: {
4227 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004228
4229 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4230 // break it apart into its prefix and identifier, then reconsititute those
4231 // as the canonical nested-name-specifier. This is required to canonicalize
4232 // a dependent nested-name-specifier involving typedefs of dependent-name
4233 // types, e.g.,
4234 // typedef typename T::type T1;
4235 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004236 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4237 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004238 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004239
Eli Friedman5358a0a2012-03-03 04:09:56 +00004240 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4241 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4242 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004243 return NestedNameSpecifier::Create(*this, nullptr, false,
4244 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004245 }
4246
4247 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004248 case NestedNameSpecifier::Super:
4249 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004250 return NNS;
4251 }
4252
David Blaikie8a40f702012-01-17 06:56:22 +00004253 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004254}
4255
Chris Lattner7adf0762008-08-04 07:31:14 +00004256
Jay Foad39c79802011-01-12 09:06:06 +00004257const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004258 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004259 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004260 // Handle the common positive case fast.
4261 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4262 return AT;
4263 }
Mike Stump11289f42009-09-09 15:08:12 +00004264
John McCall8ccfcb52009-09-24 19:53:00 +00004265 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004266 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004267 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004268
John McCall8ccfcb52009-09-24 19:53:00 +00004269 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004270 // implements C99 6.7.3p8: "If the specification of an array type includes
4271 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004272
Chris Lattner7adf0762008-08-04 07:31:14 +00004273 // If we get here, we either have type qualifiers on the type, or we have
4274 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004275 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004276
John McCall33ddac02011-01-19 10:06:00 +00004277 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004278 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004279
Chris Lattner7adf0762008-08-04 07:31:14 +00004280 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004281 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004282 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004283 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004284
Chris Lattner7adf0762008-08-04 07:31:14 +00004285 // Otherwise, we have an array and we have qualifiers on it. Push the
4286 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004287 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004288
Chris Lattner7adf0762008-08-04 07:31:14 +00004289 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4290 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4291 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004292 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004293 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4294 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4295 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004296 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004297
Mike Stump11289f42009-09-09 15:08:12 +00004298 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004299 = dyn_cast<DependentSizedArrayType>(ATy))
4300 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004301 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004302 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004303 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004304 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004305 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004306
Chris Lattner7adf0762008-08-04 07:31:14 +00004307 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004308 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004309 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004310 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004311 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004312 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004313}
4314
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004315QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004316 if (T->isArrayType() || T->isFunctionType())
4317 return getDecayedType(T);
4318 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004319}
4320
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004321QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004322 T = getVariableArrayDecayedType(T);
4323 T = getAdjustedParameterType(T);
4324 return T.getUnqualifiedType();
4325}
4326
Chris Lattnera21ad802008-04-02 05:18:44 +00004327/// getArrayDecayedType - Return the properly qualified result of decaying the
4328/// specified array type to a pointer. This operation is non-trivial when
4329/// handling typedefs etc. The canonical type of "T" must be an array type,
4330/// this returns a pointer to a properly qualified element of the array.
4331///
4332/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004333QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004334 // Get the element type with 'getAsArrayType' so that we don't lose any
4335 // typedefs in the element type of the array. This also handles propagation
4336 // of type qualifiers from the array type into the element type if present
4337 // (C99 6.7.3p8).
4338 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4339 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004340
Chris Lattner7adf0762008-08-04 07:31:14 +00004341 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004342
4343 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004344 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004345}
4346
John McCall33ddac02011-01-19 10:06:00 +00004347QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4348 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004349}
4350
John McCall33ddac02011-01-19 10:06:00 +00004351QualType ASTContext::getBaseElementType(QualType type) const {
4352 Qualifiers qs;
4353 while (true) {
4354 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004355 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004356 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004357
John McCall33ddac02011-01-19 10:06:00 +00004358 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004359 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004360 }
Mike Stump11289f42009-09-09 15:08:12 +00004361
John McCall33ddac02011-01-19 10:06:00 +00004362 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004363}
4364
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004365/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004366uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004367ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4368 uint64_t ElementCount = 1;
4369 do {
4370 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004371 CA = dyn_cast_or_null<ConstantArrayType>(
4372 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004373 } while (CA);
4374 return ElementCount;
4375}
4376
Steve Naroff0af91202007-04-27 21:51:21 +00004377/// getFloatingRank - Return a relative rank for floating point types.
4378/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004379static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004380 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004381 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004382
John McCall9dd450b2009-09-21 23:43:11 +00004383 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4384 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004385 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004386 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004387 case BuiltinType::Float: return FloatRank;
4388 case BuiltinType::Double: return DoubleRank;
4389 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004390 }
4391}
4392
Mike Stump11289f42009-09-09 15:08:12 +00004393/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4394/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004395/// 'typeDomain' is a real floating point or complex type.
4396/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004397QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4398 QualType Domain) const {
4399 FloatingRank EltRank = getFloatingRank(Size);
4400 if (Domain->isComplexType()) {
4401 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004402 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004403 case FloatRank: return FloatComplexTy;
4404 case DoubleRank: return DoubleComplexTy;
4405 case LongDoubleRank: return LongDoubleComplexTy;
4406 }
Steve Naroff0af91202007-04-27 21:51:21 +00004407 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004408
4409 assert(Domain->isRealFloatingType() && "Unknown domain!");
4410 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004411 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004412 case FloatRank: return FloatTy;
4413 case DoubleRank: return DoubleTy;
4414 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004415 }
David Blaikief47fa302012-01-17 02:30:50 +00004416 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004417}
4418
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004419/// getFloatingTypeOrder - Compare the rank of the two specified floating
4420/// point types, ignoring the domain of the type (i.e. 'double' ==
4421/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004422/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004423int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004424 FloatingRank LHSR = getFloatingRank(LHS);
4425 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004426
Chris Lattnerb90739d2008-04-06 23:38:49 +00004427 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004428 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004429 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004430 return 1;
4431 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004432}
4433
Chris Lattner76a00cf2008-04-06 22:59:24 +00004434/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4435/// routine will assert if passed a built-in type that isn't an integer or enum,
4436/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004437unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004438 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004439
Chris Lattner76a00cf2008-04-06 22:59:24 +00004440 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004441 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004442 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004443 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004444 case BuiltinType::Char_S:
4445 case BuiltinType::Char_U:
4446 case BuiltinType::SChar:
4447 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004448 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004449 case BuiltinType::Short:
4450 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004451 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004452 case BuiltinType::Int:
4453 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004454 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004455 case BuiltinType::Long:
4456 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004457 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004458 case BuiltinType::LongLong:
4459 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004460 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004461 case BuiltinType::Int128:
4462 case BuiltinType::UInt128:
4463 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004464 }
4465}
4466
Eli Friedman629ffb92009-08-20 04:21:42 +00004467/// \brief Whether this is a promotable bitfield reference according
4468/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4469///
4470/// \returns the type this bit-field will promote to, or NULL if no
4471/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004472QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004473 if (E->isTypeDependent() || E->isValueDependent())
4474 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004475
4476 // FIXME: We should not do this unless E->refersToBitField() is true. This
4477 // matters in C where getSourceBitField() will find bit-fields for various
4478 // cases where the source expression is not a bit-field designator.
4479
John McCalld25db7e2013-05-06 21:39:12 +00004480 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004481 if (!Field)
4482 return QualType();
4483
4484 QualType FT = Field->getType();
4485
Richard Smithcaf33902011-10-10 18:28:20 +00004486 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004487 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004488 // C++ [conv.prom]p5:
4489 // A prvalue for an integral bit-field can be converted to a prvalue of type
4490 // int if int can represent all the values of the bit-field; otherwise, it
4491 // can be converted to unsigned int if unsigned int can represent all the
4492 // values of the bit-field. If the bit-field is larger yet, no integral
4493 // promotion applies to it.
4494 // C11 6.3.1.1/2:
4495 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4496 // If an int can represent all values of the original type (as restricted by
4497 // the width, for a bit-field), the value is converted to an int; otherwise,
4498 // it is converted to an unsigned int.
4499 //
4500 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4501 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004502 if (BitWidth < IntSize)
4503 return IntTy;
4504
4505 if (BitWidth == IntSize)
4506 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4507
4508 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004509 // like the base type. GCC has some weird bugs in this area that we
4510 // deliberately do not follow (GCC follows a pre-standard resolution to
4511 // C's DR315 which treats bit-width as being part of the type, and this leaks
4512 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004513 return QualType();
4514}
4515
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004516/// getPromotedIntegerType - Returns the type that Promotable will
4517/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4518/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004519QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004520 assert(!Promotable.isNull());
4521 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004522 if (const EnumType *ET = Promotable->getAs<EnumType>())
4523 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004524
4525 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4526 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4527 // (3.9.1) can be converted to a prvalue of the first of the following
4528 // types that can represent all the values of its underlying type:
4529 // int, unsigned int, long int, unsigned long int, long long int, or
4530 // unsigned long long int [...]
4531 // FIXME: Is there some better way to compute this?
4532 if (BT->getKind() == BuiltinType::WChar_S ||
4533 BT->getKind() == BuiltinType::WChar_U ||
4534 BT->getKind() == BuiltinType::Char16 ||
4535 BT->getKind() == BuiltinType::Char32) {
4536 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4537 uint64_t FromSize = getTypeSize(BT);
4538 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4539 LongLongTy, UnsignedLongLongTy };
4540 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4541 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4542 if (FromSize < ToSize ||
4543 (FromSize == ToSize &&
4544 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4545 return PromoteTypes[Idx];
4546 }
4547 llvm_unreachable("char type should fit into long long");
4548 }
4549 }
4550
4551 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004552 if (Promotable->isSignedIntegerType())
4553 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004554 uint64_t PromotableSize = getIntWidth(Promotable);
4555 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004556 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4557 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4558}
4559
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004560/// \brief Recurses in pointer/array types until it finds an objc retainable
4561/// type and returns its ownership.
4562Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4563 while (!T.isNull()) {
4564 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4565 return T.getObjCLifetime();
4566 if (T->isArrayType())
4567 T = getBaseElementType(T);
4568 else if (const PointerType *PT = T->getAs<PointerType>())
4569 T = PT->getPointeeType();
4570 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004571 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004572 else
4573 break;
4574 }
4575
4576 return Qualifiers::OCL_None;
4577}
4578
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004579static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4580 // Incomplete enum types are not treated as integer types.
4581 // FIXME: In C++, enum types are never integer types.
4582 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4583 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004584 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004585}
4586
Mike Stump11289f42009-09-09 15:08:12 +00004587/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004588/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004589/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004590int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004591 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4592 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004593
4594 // Unwrap enums to their underlying type.
4595 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4596 LHSC = getIntegerTypeForEnum(ET);
4597 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4598 RHSC = getIntegerTypeForEnum(ET);
4599
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004600 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004601
Chris Lattner76a00cf2008-04-06 22:59:24 +00004602 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4603 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004604
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004605 unsigned LHSRank = getIntegerRank(LHSC);
4606 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004607
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004608 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4609 if (LHSRank == RHSRank) return 0;
4610 return LHSRank > RHSRank ? 1 : -1;
4611 }
Mike Stump11289f42009-09-09 15:08:12 +00004612
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004613 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4614 if (LHSUnsigned) {
4615 // If the unsigned [LHS] type is larger, return it.
4616 if (LHSRank >= RHSRank)
4617 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004618
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004619 // If the signed type can represent all values of the unsigned type, it
4620 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004621 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004622 return -1;
4623 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004624
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004625 // If the unsigned [RHS] type is larger, return it.
4626 if (RHSRank >= LHSRank)
4627 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004628
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004629 // If the signed type can represent all values of the unsigned type, it
4630 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004631 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004632 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004633}
Anders Carlsson98f07902007-08-17 05:31:46 +00004634
Mike Stump11289f42009-09-09 15:08:12 +00004635// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004636QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004637 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004638 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004639 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004640
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004641 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004642
Anders Carlsson98f07902007-08-17 05:31:46 +00004643 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004644 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004645 // int flags;
4646 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004647 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004648 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004649 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004650 FieldTypes[3] = LongTy;
4651
Anders Carlsson98f07902007-08-17 05:31:46 +00004652 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004653 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004654 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004655 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004656 SourceLocation(), nullptr,
4657 FieldTypes[i], /*TInfo=*/nullptr,
4658 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004659 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004660 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004661 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004662 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004663 }
4664
Douglas Gregord5058122010-02-11 01:19:42 +00004665 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004666 }
Mike Stump11289f42009-09-09 15:08:12 +00004667
Anders Carlsson98f07902007-08-17 05:31:46 +00004668 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004669}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004670
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004671QualType ASTContext::getObjCSuperType() const {
4672 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004673 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004674 TUDecl->addDecl(ObjCSuperTypeDecl);
4675 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4676 }
4677 return ObjCSuperType;
4678}
4679
Douglas Gregor512b0772009-04-23 22:29:11 +00004680void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004681 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004682 assert(Rec && "Invalid CFConstantStringType");
4683 CFConstantStringTypeDecl = Rec->getDecl();
4684}
4685
Jay Foad39c79802011-01-12 09:06:06 +00004686QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004687 if (BlockDescriptorType)
4688 return getTagDeclType(BlockDescriptorType);
4689
Alp Toker2dea15b2013-12-17 01:22:38 +00004690 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004691 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004692 RD = buildImplicitRecord("__block_descriptor");
4693 RD->startDefinition();
4694
Mike Stumpd0153282009-10-20 02:12:22 +00004695 QualType FieldTypes[] = {
4696 UnsignedLongTy,
4697 UnsignedLongTy,
4698 };
4699
Craig Topperd6d31ac2013-07-15 08:24:27 +00004700 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004701 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004702 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004703 };
4704
4705 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004706 FieldDecl *Field = FieldDecl::Create(
4707 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004708 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4709 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004710 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004711 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004712 }
4713
Alp Toker2dea15b2013-12-17 01:22:38 +00004714 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004715
Alp Toker2dea15b2013-12-17 01:22:38 +00004716 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004717
4718 return getTagDeclType(BlockDescriptorType);
4719}
4720
Jay Foad39c79802011-01-12 09:06:06 +00004721QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004722 if (BlockDescriptorExtendedType)
4723 return getTagDeclType(BlockDescriptorExtendedType);
4724
Alp Toker2dea15b2013-12-17 01:22:38 +00004725 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004726 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004727 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4728 RD->startDefinition();
4729
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004730 QualType FieldTypes[] = {
4731 UnsignedLongTy,
4732 UnsignedLongTy,
4733 getPointerType(VoidPtrTy),
4734 getPointerType(VoidPtrTy)
4735 };
4736
Craig Topperd6d31ac2013-07-15 08:24:27 +00004737 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004738 "reserved",
4739 "Size",
4740 "CopyFuncPtr",
4741 "DestroyFuncPtr"
4742 };
4743
4744 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004745 FieldDecl *Field = FieldDecl::Create(
4746 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004747 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4748 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004749 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004750 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004751 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004752 }
4753
Alp Toker2dea15b2013-12-17 01:22:38 +00004754 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004755
Alp Toker2dea15b2013-12-17 01:22:38 +00004756 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004757 return getTagDeclType(BlockDescriptorExtendedType);
4758}
4759
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004760/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4761/// requires copy/dispose. Note that this must match the logic
4762/// in buildByrefHelpers.
4763bool ASTContext::BlockRequiresCopying(QualType Ty,
4764 const VarDecl *D) {
4765 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4766 const Expr *copyExpr = getBlockVarCopyInits(D);
4767 if (!copyExpr && record->hasTrivialDestructor()) return false;
4768
Mike Stump94967902009-10-21 18:16:27 +00004769 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004770 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004771
4772 if (!Ty->isObjCRetainableType()) return false;
4773
4774 Qualifiers qs = Ty.getQualifiers();
4775
4776 // If we have lifetime, that dominates.
4777 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4778 assert(getLangOpts().ObjCAutoRefCount);
4779
4780 switch (lifetime) {
4781 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4782
4783 // These are just bits as far as the runtime is concerned.
4784 case Qualifiers::OCL_ExplicitNone:
4785 case Qualifiers::OCL_Autoreleasing:
4786 return false;
4787
4788 // Tell the runtime that this is ARC __weak, called by the
4789 // byref routines.
4790 case Qualifiers::OCL_Weak:
4791 // ARC __strong __block variables need to be retained.
4792 case Qualifiers::OCL_Strong:
4793 return true;
4794 }
4795 llvm_unreachable("fell out of lifetime switch!");
4796 }
4797 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4798 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004799}
4800
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004801bool ASTContext::getByrefLifetime(QualType Ty,
4802 Qualifiers::ObjCLifetime &LifeTime,
4803 bool &HasByrefExtendedLayout) const {
4804
4805 if (!getLangOpts().ObjC1 ||
4806 getLangOpts().getGC() != LangOptions::NonGC)
4807 return false;
4808
4809 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004810 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004811 HasByrefExtendedLayout = true;
4812 LifeTime = Qualifiers::OCL_None;
4813 }
4814 else if (getLangOpts().ObjCAutoRefCount)
4815 LifeTime = Ty.getObjCLifetime();
4816 // MRR.
4817 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4818 LifeTime = Qualifiers::OCL_ExplicitNone;
4819 else
4820 LifeTime = Qualifiers::OCL_None;
4821 return true;
4822}
4823
Douglas Gregorbab8a962011-09-08 01:46:34 +00004824TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4825 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004826 ObjCInstanceTypeDecl =
4827 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004828 return ObjCInstanceTypeDecl;
4829}
4830
Anders Carlsson18acd442007-10-29 06:33:42 +00004831// This returns true if a type has been typedefed to BOOL:
4832// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004833static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004834 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004835 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4836 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004837
Anders Carlssond8499822007-10-29 05:01:08 +00004838 return false;
4839}
4840
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004841/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004842/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004843CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004844 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4845 return CharUnits::Zero();
4846
Ken Dyck40775002010-01-11 17:06:35 +00004847 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004848
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004849 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004850 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004851 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004852 // Treat arrays as pointers, since that's how they're passed in.
4853 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004854 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004855 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004856}
4857
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004858bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4859 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4860 VD->getType()->isIntegralOrEnumerationType() &&
4861 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4862}
4863
Ken Dyck40775002010-01-11 17:06:35 +00004864static inline
4865std::string charUnitsToString(const CharUnits &CU) {
4866 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004867}
4868
John McCall351762c2011-02-07 10:33:21 +00004869/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004870/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004871std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4872 std::string S;
4873
David Chisnall950a9512009-11-17 19:33:30 +00004874 const BlockDecl *Decl = Expr->getBlockDecl();
4875 QualType BlockTy =
4876 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4877 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004878 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004879 getObjCEncodingForMethodParameter(
4880 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4881 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004882 else
Alp Toker314cc812014-01-25 16:55:45 +00004883 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004884 // Compute size of all parameters.
4885 // Start with computing size of a pointer in number of bytes.
4886 // FIXME: There might(should) be a better way of doing this computation!
4887 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004888 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4889 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004890 for (auto PI : Decl->params()) {
4891 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004892 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004893 if (sz.isZero())
4894 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004895 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004896 ParmOffset += sz;
4897 }
4898 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004899 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004900 // Block pointer and offset.
4901 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004902
4903 // Argument types.
4904 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004905 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004906 QualType PType = PVDecl->getOriginalType();
4907 if (const ArrayType *AT =
4908 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4909 // Use array's original type only if it has known number of
4910 // elements.
4911 if (!isa<ConstantArrayType>(AT))
4912 PType = PVDecl->getType();
4913 } else if (PType->isFunctionType())
4914 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004915 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004916 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4917 S, true /*Extended*/);
4918 else
4919 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004920 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004921 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004922 }
John McCall351762c2011-02-07 10:33:21 +00004923
4924 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004925}
4926
Douglas Gregora9d84932011-05-27 01:19:52 +00004927bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004928 std::string& S) {
4929 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004930 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004931 CharUnits ParmOffset;
4932 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004933 for (auto PI : Decl->params()) {
4934 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004935 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004936 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004937 continue;
4938
David Chisnall50e4eba2010-12-30 14:05:53 +00004939 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004940 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004941 ParmOffset += sz;
4942 }
4943 S += charUnitsToString(ParmOffset);
4944 ParmOffset = CharUnits::Zero();
4945
4946 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004947 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004948 QualType PType = PVDecl->getOriginalType();
4949 if (const ArrayType *AT =
4950 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4951 // Use array's original type only if it has known number of
4952 // elements.
4953 if (!isa<ConstantArrayType>(AT))
4954 PType = PVDecl->getType();
4955 } else if (PType->isFunctionType())
4956 PType = PVDecl->getType();
4957 getObjCEncodingForType(PType, S);
4958 S += charUnitsToString(ParmOffset);
4959 ParmOffset += getObjCEncodingTypeSize(PType);
4960 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004961
4962 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004963}
4964
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004965/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4966/// method parameter or return type. If Extended, include class names and
4967/// block object types.
4968void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4969 QualType T, std::string& S,
4970 bool Extended) const {
4971 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4972 getObjCEncodingForTypeQualifier(QT, S);
4973 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00004974 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004975 true /*OutermostType*/,
4976 false /*EncodingProperty*/,
4977 false /*StructField*/,
4978 Extended /*EncodeBlockParameters*/,
4979 Extended /*EncodeClassNames*/);
4980}
4981
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004982/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004983/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004984bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004985 std::string& S,
4986 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004987 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004988 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004989 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4990 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004991 // Compute size of all parameters.
4992 // Start with computing size of a pointer in number of bytes.
4993 // FIXME: There might(should) be a better way of doing this computation!
4994 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004995 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004996 // The first two arguments (self and _cmd) are pointers; account for
4997 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004998 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004999 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005000 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005001 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005002 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005003 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005004 continue;
5005
Ken Dyck40775002010-01-11 17:06:35 +00005006 assert (sz.isPositive() &&
5007 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005008 ParmOffset += sz;
5009 }
Ken Dyck40775002010-01-11 17:06:35 +00005010 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005011 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005012 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005013
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005014 // Argument types.
5015 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005016 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005017 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005018 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005019 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005020 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005021 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5022 // Use array's original type only if it has known number of
5023 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005024 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005025 PType = PVDecl->getType();
5026 } else if (PType->isFunctionType())
5027 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005028 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5029 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005030 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005031 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005032 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005033
5034 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005035}
5036
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005037ObjCPropertyImplDecl *
5038ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5039 const ObjCPropertyDecl *PD,
5040 const Decl *Container) const {
5041 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005042 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005043 if (const ObjCCategoryImplDecl *CID =
5044 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005045 for (auto *PID : CID->property_impls())
5046 if (PID->getPropertyDecl() == PD)
5047 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005048 } else {
5049 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5050 for (auto *PID : OID->property_impls())
5051 if (PID->getPropertyDecl() == PD)
5052 return PID;
5053 }
5054 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005055}
5056
Daniel Dunbar4932b362008-08-28 04:38:10 +00005057/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005058/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005059/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5060/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005061/// Property attributes are stored as a comma-delimited C string. The simple
5062/// attributes readonly and bycopy are encoded as single characters. The
5063/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5064/// encoded as single characters, followed by an identifier. Property types
5065/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005066/// these attributes are defined by the following enumeration:
5067/// @code
5068/// enum PropertyAttributes {
5069/// kPropertyReadOnly = 'R', // property is read-only.
5070/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5071/// kPropertyByref = '&', // property is a reference to the value last assigned
5072/// kPropertyDynamic = 'D', // property is dynamic
5073/// kPropertyGetter = 'G', // followed by getter selector name
5074/// kPropertySetter = 'S', // followed by setter selector name
5075/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005076/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005077/// kPropertyWeak = 'W' // 'weak' property
5078/// kPropertyStrong = 'P' // property GC'able
5079/// kPropertyNonAtomic = 'N' // property non-atomic
5080/// };
5081/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005082void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005083 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005084 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005085 // Collect information from the property implementation decl(s).
5086 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005087 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005088
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005089 if (ObjCPropertyImplDecl *PropertyImpDecl =
5090 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5091 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5092 Dynamic = true;
5093 else
5094 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005095 }
5096
5097 // FIXME: This is not very efficient.
5098 S = "T";
5099
5100 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005101 // GCC has some special rules regarding encoding of properties which
5102 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005103 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005104
5105 if (PD->isReadOnly()) {
5106 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005107 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5108 S += ",C";
5109 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5110 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005111 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5112 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005113 } else {
5114 switch (PD->getSetterKind()) {
5115 case ObjCPropertyDecl::Assign: break;
5116 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005117 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005118 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005119 }
5120 }
5121
5122 // It really isn't clear at all what this means, since properties
5123 // are "dynamic by default".
5124 if (Dynamic)
5125 S += ",D";
5126
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005127 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5128 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005129
Daniel Dunbar4932b362008-08-28 04:38:10 +00005130 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5131 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005132 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005133 }
5134
5135 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5136 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005137 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005138 }
5139
5140 if (SynthesizePID) {
5141 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5142 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005143 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005144 }
5145
5146 // FIXME: OBJCGC: weak & strong
5147}
5148
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005149/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005150/// Another legacy compatibility encoding: 32-bit longs are encoded as
5151/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005152/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5153///
5154void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005155 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005156 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005157 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005158 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005159 else
Jay Foad39c79802011-01-12 09:06:06 +00005160 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005161 PointeeTy = IntTy;
5162 }
5163 }
5164}
5165
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005166void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005167 const FieldDecl *Field,
5168 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005169 // We follow the behavior of gcc, expanding structures which are
5170 // directly pointed to, and expanding embedded structures. Note that
5171 // these rules are sufficient to prevent recursive encoding of the
5172 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005173 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005174 true /* outermost type */, false, false,
5175 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005176}
5177
Joe Groff98ac7d22014-07-07 22:25:15 +00005178void ASTContext::getObjCEncodingForPropertyType(QualType T,
5179 std::string& S) const {
5180 // Encode result type.
5181 // GCC has some special rules regarding encoding of properties which
5182 // closely resembles encoding of ivars.
5183 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5184 true /* outermost type */,
5185 true /* encoding property */);
5186}
5187
John McCall393a78d2012-12-20 02:45:14 +00005188static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5189 BuiltinType::Kind kind) {
5190 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005191 case BuiltinType::Void: return 'v';
5192 case BuiltinType::Bool: return 'B';
5193 case BuiltinType::Char_U:
5194 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005195 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005196 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005197 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005198 case BuiltinType::UInt: return 'I';
5199 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005200 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005201 case BuiltinType::UInt128: return 'T';
5202 case BuiltinType::ULongLong: return 'Q';
5203 case BuiltinType::Char_S:
5204 case BuiltinType::SChar: return 'c';
5205 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005206 case BuiltinType::WChar_S:
5207 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005208 case BuiltinType::Int: return 'i';
5209 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005210 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005211 case BuiltinType::LongLong: return 'q';
5212 case BuiltinType::Int128: return 't';
5213 case BuiltinType::Float: return 'f';
5214 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005215 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005216 case BuiltinType::NullPtr: return '*'; // like char*
5217
5218 case BuiltinType::Half:
5219 // FIXME: potentially need @encodes for these!
5220 return ' ';
5221
5222 case BuiltinType::ObjCId:
5223 case BuiltinType::ObjCClass:
5224 case BuiltinType::ObjCSel:
5225 llvm_unreachable("@encoding ObjC primitive type");
5226
5227 // OpenCL and placeholder types don't need @encodings.
5228 case BuiltinType::OCLImage1d:
5229 case BuiltinType::OCLImage1dArray:
5230 case BuiltinType::OCLImage1dBuffer:
5231 case BuiltinType::OCLImage2d:
5232 case BuiltinType::OCLImage2dArray:
5233 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005234 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005235 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005236 case BuiltinType::Dependent:
5237#define BUILTIN_TYPE(KIND, ID)
5238#define PLACEHOLDER_TYPE(KIND, ID) \
5239 case BuiltinType::KIND:
5240#include "clang/AST/BuiltinTypes.def"
5241 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005242 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005243 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005244}
5245
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005246static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5247 EnumDecl *Enum = ET->getDecl();
5248
5249 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5250 if (!Enum->isFixed())
5251 return 'i';
5252
5253 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005254 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5255 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005256}
5257
Jay Foad39c79802011-01-12 09:06:06 +00005258static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005259 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005260 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005261 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005262 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5263 // The GNU runtime requires more information; bitfields are encoded as b,
5264 // then the offset (in bits) of the first element, then the type of the
5265 // bitfield, then the size in bits. For example, in this structure:
5266 //
5267 // struct
5268 // {
5269 // int integer;
5270 // int flags:2;
5271 // };
5272 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5273 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5274 // information is not especially sensible, but we're stuck with it for
5275 // compatibility with GCC, although providing it breaks anything that
5276 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005277 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005278 const RecordDecl *RD = FD->getParent();
5279 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005280 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005281 if (const EnumType *ET = T->getAs<EnumType>())
5282 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005283 else {
5284 const BuiltinType *BT = T->castAs<BuiltinType>();
5285 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5286 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005287 }
Richard Smithcaf33902011-10-10 18:28:20 +00005288 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005289}
5290
Daniel Dunbar07d07852009-10-18 21:17:35 +00005291// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005292void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5293 bool ExpandPointedToStructures,
5294 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005295 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005296 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005297 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005298 bool StructField,
5299 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005300 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005301 bool EncodePointerToObjCTypedef,
5302 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005303 CanQualType CT = getCanonicalType(T);
5304 switch (CT->getTypeClass()) {
5305 case Type::Builtin:
5306 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005307 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005308 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005309 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5310 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5311 else
5312 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005313 return;
Mike Stump11289f42009-09-09 15:08:12 +00005314
John McCall393a78d2012-12-20 02:45:14 +00005315 case Type::Complex: {
5316 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005317 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005318 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005319 return;
5320 }
John McCall393a78d2012-12-20 02:45:14 +00005321
5322 case Type::Atomic: {
5323 const AtomicType *AT = T->castAs<AtomicType>();
5324 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005325 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005326 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005327 }
John McCall393a78d2012-12-20 02:45:14 +00005328
5329 // encoding for pointer or reference types.
5330 case Type::Pointer:
5331 case Type::LValueReference:
5332 case Type::RValueReference: {
5333 QualType PointeeTy;
5334 if (isa<PointerType>(CT)) {
5335 const PointerType *PT = T->castAs<PointerType>();
5336 if (PT->isObjCSelType()) {
5337 S += ':';
5338 return;
5339 }
5340 PointeeTy = PT->getPointeeType();
5341 } else {
5342 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5343 }
5344
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005345 bool isReadOnly = false;
5346 // For historical/compatibility reasons, the read-only qualifier of the
5347 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5348 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005349 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005350 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005351 if (OutermostType && T.isConstQualified()) {
5352 isReadOnly = true;
5353 S += 'r';
5354 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005355 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005356 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005357 while (P->getAs<PointerType>())
5358 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005359 if (P.isConstQualified()) {
5360 isReadOnly = true;
5361 S += 'r';
5362 }
5363 }
5364 if (isReadOnly) {
5365 // Another legacy compatibility encoding. Some ObjC qualifier and type
5366 // combinations need to be rearranged.
5367 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005368 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005369 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005370 }
Mike Stump11289f42009-09-09 15:08:12 +00005371
Anders Carlssond8499822007-10-29 05:01:08 +00005372 if (PointeeTy->isCharType()) {
5373 // char pointer types should be encoded as '*' unless it is a
5374 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005375 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005376 S += '*';
5377 return;
5378 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005379 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005380 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5381 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5382 S += '#';
5383 return;
5384 }
5385 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5386 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5387 S += '@';
5388 return;
5389 }
5390 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005391 }
Anders Carlssond8499822007-10-29 05:01:08 +00005392 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005393 getLegacyIntegralTypeEncoding(PointeeTy);
5394
Mike Stump11289f42009-09-09 15:08:12 +00005395 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005396 nullptr, false, false, false, false, false, false,
5397 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005398 return;
5399 }
John McCall393a78d2012-12-20 02:45:14 +00005400
5401 case Type::ConstantArray:
5402 case Type::IncompleteArray:
5403 case Type::VariableArray: {
5404 const ArrayType *AT = cast<ArrayType>(CT);
5405
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005406 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005407 // Incomplete arrays are encoded as a pointer to the array element.
5408 S += '^';
5409
Mike Stump11289f42009-09-09 15:08:12 +00005410 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005411 false, ExpandStructures, FD);
5412 } else {
5413 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005414
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005415 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5416 S += llvm::utostr(CAT->getSize().getZExtValue());
5417 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005418 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005419 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5420 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005421 S += '0';
5422 }
Mike Stump11289f42009-09-09 15:08:12 +00005423
5424 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005425 false, ExpandStructures, FD,
5426 false, false, false, false, false, false,
5427 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005428 S += ']';
5429 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005430 return;
5431 }
Mike Stump11289f42009-09-09 15:08:12 +00005432
John McCall393a78d2012-12-20 02:45:14 +00005433 case Type::FunctionNoProto:
5434 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005435 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005436 return;
Mike Stump11289f42009-09-09 15:08:12 +00005437
John McCall393a78d2012-12-20 02:45:14 +00005438 case Type::Record: {
5439 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005440 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005441 // Anonymous structures print as '?'
5442 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5443 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005444 if (ClassTemplateSpecializationDecl *Spec
5445 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5446 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005447 llvm::raw_string_ostream OS(S);
5448 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005449 TemplateArgs.data(),
5450 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005451 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005452 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005453 } else {
5454 S += '?';
5455 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005456 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005457 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005458 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005459 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005460 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005461 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005462 if (FD) {
5463 S += '"';
5464 S += Field->getNameAsString();
5465 S += '"';
5466 }
Mike Stump11289f42009-09-09 15:08:12 +00005467
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005468 // Special case bit-fields.
5469 if (Field->isBitField()) {
5470 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005471 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005472 } else {
5473 QualType qt = Field->getType();
5474 getLegacyIntegralTypeEncoding(qt);
5475 getObjCEncodingForTypeImpl(qt, S, false, true,
5476 FD, /*OutermostType*/false,
5477 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005478 /*StructField*/true,
5479 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005480 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005481 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005482 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005483 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005484 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005485 return;
5486 }
Mike Stump11289f42009-09-09 15:08:12 +00005487
John McCall393a78d2012-12-20 02:45:14 +00005488 case Type::BlockPointer: {
5489 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005490 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005491 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005492 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005493
5494 S += '<';
5495 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005496 getObjCEncodingForTypeImpl(
5497 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5498 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005499 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5500 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005501 // Block self
5502 S += "@?";
5503 // Block parameters
5504 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005505 for (const auto &I : FPT->param_types())
5506 getObjCEncodingForTypeImpl(
5507 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5508 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005509 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5510 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005511 }
5512 S += '>';
5513 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005514 return;
5515 }
Mike Stump11289f42009-09-09 15:08:12 +00005516
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005517 case Type::ObjCObject: {
5518 // hack to match legacy encoding of *id and *Class
5519 QualType Ty = getObjCObjectPointerType(CT);
5520 if (Ty->isObjCIdType()) {
5521 S += "{objc_object=}";
5522 return;
5523 }
5524 else if (Ty->isObjCClassType()) {
5525 S += "{objc_class=}";
5526 return;
5527 }
5528 }
5529
John McCall393a78d2012-12-20 02:45:14 +00005530 case Type::ObjCInterface: {
5531 // Ignore protocol qualifiers when mangling at this level.
5532 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005533
John McCall393a78d2012-12-20 02:45:14 +00005534 // The assumption seems to be that this assert will succeed
5535 // because nested levels will have filtered out 'id' and 'Class'.
5536 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005537 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005538 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005539 S += '{';
5540 const IdentifierInfo *II = OI->getIdentifier();
5541 S += II->getName();
5542 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005543 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005544 DeepCollectObjCIvars(OI, true, Ivars);
5545 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005546 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005547 if (Field->isBitField())
5548 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005549 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005550 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5551 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005552 EncodePointerToObjCTypedef,
5553 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005554 }
5555 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005556 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005557 }
Mike Stump11289f42009-09-09 15:08:12 +00005558
John McCall393a78d2012-12-20 02:45:14 +00005559 case Type::ObjCObjectPointer: {
5560 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005561 if (OPT->isObjCIdType()) {
5562 S += '@';
5563 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005564 }
Mike Stump11289f42009-09-09 15:08:12 +00005565
Steve Narofff0c86112009-10-28 22:03:49 +00005566 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5567 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5568 // Since this is a binary compatibility issue, need to consult with runtime
5569 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005570 S += '#';
5571 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005572 }
Mike Stump11289f42009-09-09 15:08:12 +00005573
Chris Lattnere7cabb92009-07-13 00:10:46 +00005574 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005575 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005576 ExpandPointedToStructures,
5577 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005578 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005579 // Note that we do extended encoding of protocol qualifer list
5580 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005581 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005582 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005583 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005584 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005585 S += '>';
5586 }
5587 S += '"';
5588 }
5589 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005590 }
Mike Stump11289f42009-09-09 15:08:12 +00005591
Chris Lattnere7cabb92009-07-13 00:10:46 +00005592 QualType PointeeTy = OPT->getPointeeType();
5593 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005594 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5595 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005596 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005597 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005598 // {...};
5599 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005600 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005601 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005602 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5603 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5604 DeepCollectObjCIvars(OI, true, Ivars);
5605 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5606 if (cast<FieldDecl>(Ivars[i]) == FD) {
5607 S += '{';
5608 S += OI->getIdentifier()->getName();
5609 S += '}';
5610 return;
5611 }
5612 }
5613 }
Mike Stump11289f42009-09-09 15:08:12 +00005614 getObjCEncodingForTypeImpl(PointeeTy, S,
5615 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005616 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005617 false, false, false, false, false,
5618 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005619 return;
5620 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005621
5622 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005623 if (OPT->getInterfaceDecl() &&
5624 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005625 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005626 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005627 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005628 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005629 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005630 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005631 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005632 S += '"';
5633 }
5634 return;
5635 }
Mike Stump11289f42009-09-09 15:08:12 +00005636
John McCalla9e6e8d2010-05-17 23:56:34 +00005637 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005638 // FIXME: we shoul do better than that. 'M' is available.
5639 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005640 // This matches gcc's encoding, even though technically it is insufficient.
5641 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005642 case Type::Vector:
5643 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005644 // Until we have a coherent encoding of these three types, issue warning.
5645 { if (NotEncodedT)
5646 *NotEncodedT = T;
5647 return;
5648 }
5649
5650 // We could see an undeduced auto type here during error recovery.
5651 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005652 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005653 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005654
Richard Smith27d807c2013-04-30 13:56:41 +00005655
John McCall393a78d2012-12-20 02:45:14 +00005656#define ABSTRACT_TYPE(KIND, BASE)
5657#define TYPE(KIND, BASE)
5658#define DEPENDENT_TYPE(KIND, BASE) \
5659 case Type::KIND:
5660#define NON_CANONICAL_TYPE(KIND, BASE) \
5661 case Type::KIND:
5662#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5663 case Type::KIND:
5664#include "clang/AST/TypeNodes.def"
5665 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005666 }
John McCall393a78d2012-12-20 02:45:14 +00005667 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005668}
5669
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005670void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5671 std::string &S,
5672 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005673 bool includeVBases,
5674 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005675 assert(RDecl && "Expected non-null RecordDecl");
5676 assert(!RDecl->isUnion() && "Should not be called for unions");
5677 if (!RDecl->getDefinition())
5678 return;
5679
5680 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5681 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5682 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5683
5684 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005685 for (const auto &BI : CXXRec->bases()) {
5686 if (!BI.isVirtual()) {
5687 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005688 if (base->isEmpty())
5689 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005690 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005691 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5692 std::make_pair(offs, base));
5693 }
5694 }
5695 }
5696
5697 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005698 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005699 uint64_t offs = layout.getFieldOffset(i);
5700 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005701 std::make_pair(offs, Field));
5702 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005703 }
5704
5705 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005706 for (const auto &BI : CXXRec->vbases()) {
5707 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005708 if (base->isEmpty())
5709 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005710 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005711 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5712 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005713 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5714 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005715 }
5716 }
5717
5718 CharUnits size;
5719 if (CXXRec) {
5720 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5721 } else {
5722 size = layout.getSize();
5723 }
5724
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005725#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005726 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005727#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005728 std::multimap<uint64_t, NamedDecl *>::iterator
5729 CurLayObj = FieldOrBaseOffsets.begin();
5730
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005731 if (CXXRec && CXXRec->isDynamicClass() &&
5732 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005733 if (FD) {
5734 S += "\"_vptr$";
5735 std::string recname = CXXRec->getNameAsString();
5736 if (recname.empty()) recname = "?";
5737 S += recname;
5738 S += '"';
5739 }
5740 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005741#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005742 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005743#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005744 }
5745
5746 if (!RDecl->hasFlexibleArrayMember()) {
5747 // Mark the end of the structure.
5748 uint64_t offs = toBits(size);
5749 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005750 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005751 }
5752
5753 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005754#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005755 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005756 if (CurOffs < CurLayObj->first) {
5757 uint64_t padding = CurLayObj->first - CurOffs;
5758 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5759 // packing/alignment of members is different that normal, in which case
5760 // the encoding will be out-of-sync with the real layout.
5761 // If the runtime switches to just consider the size of types without
5762 // taking into account alignment, we could make padding explicit in the
5763 // encoding (e.g. using arrays of chars). The encoding strings would be
5764 // longer then though.
5765 CurOffs += padding;
5766 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005767#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005768
5769 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005770 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005771 break; // reached end of structure.
5772
5773 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5774 // We expand the bases without their virtual bases since those are going
5775 // in the initial structure. Note that this differs from gcc which
5776 // expands virtual bases each time one is encountered in the hierarchy,
5777 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005778 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5779 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005780 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005781#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005782 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005783#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005784 } else {
5785 FieldDecl *field = cast<FieldDecl>(dcl);
5786 if (FD) {
5787 S += '"';
5788 S += field->getNameAsString();
5789 S += '"';
5790 }
5791
5792 if (field->isBitField()) {
5793 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005794#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005795 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005796#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005797 } else {
5798 QualType qt = field->getType();
5799 getLegacyIntegralTypeEncoding(qt);
5800 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5801 /*OutermostType*/false,
5802 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005803 /*StructField*/true,
5804 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005805#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005806 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005807#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005808 }
5809 }
5810 }
5811}
5812
Mike Stump11289f42009-09-09 15:08:12 +00005813void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005814 std::string& S) const {
5815 if (QT & Decl::OBJC_TQ_In)
5816 S += 'n';
5817 if (QT & Decl::OBJC_TQ_Inout)
5818 S += 'N';
5819 if (QT & Decl::OBJC_TQ_Out)
5820 S += 'o';
5821 if (QT & Decl::OBJC_TQ_Bycopy)
5822 S += 'O';
5823 if (QT & Decl::OBJC_TQ_Byref)
5824 S += 'R';
5825 if (QT & Decl::OBJC_TQ_Oneway)
5826 S += 'V';
5827}
5828
Douglas Gregor3ea72692011-08-12 05:46:01 +00005829TypedefDecl *ASTContext::getObjCIdDecl() const {
5830 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005831 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005832 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005833 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005834 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005835 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005836}
5837
Douglas Gregor52e02802011-08-12 06:17:30 +00005838TypedefDecl *ASTContext::getObjCSelDecl() const {
5839 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005840 QualType T = getPointerType(ObjCBuiltinSelTy);
5841 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005842 }
5843 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005844}
5845
Douglas Gregor0a586182011-08-12 05:59:41 +00005846TypedefDecl *ASTContext::getObjCClassDecl() const {
5847 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005848 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005849 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005850 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005851 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005852 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005853}
5854
Douglas Gregord53ae832012-01-17 18:09:05 +00005855ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5856 if (!ObjCProtocolClassDecl) {
5857 ObjCProtocolClassDecl
5858 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5859 SourceLocation(),
5860 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005861 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005862 SourceLocation(), true);
5863 }
5864
5865 return ObjCProtocolClassDecl;
5866}
5867
Meador Inge5d3fb222012-06-16 03:34:49 +00005868//===----------------------------------------------------------------------===//
5869// __builtin_va_list Construction Functions
5870//===----------------------------------------------------------------------===//
5871
5872static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5873 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005874 QualType T = Context->getPointerType(Context->CharTy);
5875 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005876}
5877
5878static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5879 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005880 QualType T = Context->getPointerType(Context->VoidTy);
5881 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005882}
5883
Tim Northover9bb857a2013-01-31 12:13:10 +00005884static TypedefDecl *
5885CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005886 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005887 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005888 if (Context->getLangOpts().CPlusPlus) {
5889 // namespace std { struct __va_list {
5890 NamespaceDecl *NS;
5891 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5892 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005893 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005894 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005895 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005896 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005897 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005898 }
5899
5900 VaListTagDecl->startDefinition();
5901
5902 const size_t NumFields = 5;
5903 QualType FieldTypes[NumFields];
5904 const char *FieldNames[NumFields];
5905
5906 // void *__stack;
5907 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5908 FieldNames[0] = "__stack";
5909
5910 // void *__gr_top;
5911 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5912 FieldNames[1] = "__gr_top";
5913
5914 // void *__vr_top;
5915 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5916 FieldNames[2] = "__vr_top";
5917
5918 // int __gr_offs;
5919 FieldTypes[3] = Context->IntTy;
5920 FieldNames[3] = "__gr_offs";
5921
5922 // int __vr_offs;
5923 FieldTypes[4] = Context->IntTy;
5924 FieldNames[4] = "__vr_offs";
5925
5926 // Create fields
5927 for (unsigned i = 0; i < NumFields; ++i) {
5928 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5929 VaListTagDecl,
5930 SourceLocation(),
5931 SourceLocation(),
5932 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005933 FieldTypes[i], /*TInfo=*/nullptr,
5934 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005935 /*Mutable=*/false,
5936 ICIS_NoInit);
5937 Field->setAccess(AS_public);
5938 VaListTagDecl->addDecl(Field);
5939 }
5940 VaListTagDecl->completeDefinition();
5941 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5942 Context->VaListTagTy = VaListTagType;
5943
5944 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005945 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005946}
5947
Meador Inge5d3fb222012-06-16 03:34:49 +00005948static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5949 // typedef struct __va_list_tag {
5950 RecordDecl *VaListTagDecl;
5951
Alp Toker2dea15b2013-12-17 01:22:38 +00005952 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005953 VaListTagDecl->startDefinition();
5954
5955 const size_t NumFields = 5;
5956 QualType FieldTypes[NumFields];
5957 const char *FieldNames[NumFields];
5958
5959 // unsigned char gpr;
5960 FieldTypes[0] = Context->UnsignedCharTy;
5961 FieldNames[0] = "gpr";
5962
5963 // unsigned char fpr;
5964 FieldTypes[1] = Context->UnsignedCharTy;
5965 FieldNames[1] = "fpr";
5966
5967 // unsigned short reserved;
5968 FieldTypes[2] = Context->UnsignedShortTy;
5969 FieldNames[2] = "reserved";
5970
5971 // void* overflow_arg_area;
5972 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5973 FieldNames[3] = "overflow_arg_area";
5974
5975 // void* reg_save_area;
5976 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5977 FieldNames[4] = "reg_save_area";
5978
5979 // Create fields
5980 for (unsigned i = 0; i < NumFields; ++i) {
5981 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5982 SourceLocation(),
5983 SourceLocation(),
5984 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005985 FieldTypes[i], /*TInfo=*/nullptr,
5986 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00005987 /*Mutable=*/false,
5988 ICIS_NoInit);
5989 Field->setAccess(AS_public);
5990 VaListTagDecl->addDecl(Field);
5991 }
5992 VaListTagDecl->completeDefinition();
5993 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005994 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005995
5996 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005997 TypedefDecl *VaListTagTypedefDecl =
5998 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5999
Meador Inge5d3fb222012-06-16 03:34:49 +00006000 QualType VaListTagTypedefType =
6001 Context->getTypedefType(VaListTagTypedefDecl);
6002
6003 // typedef __va_list_tag __builtin_va_list[1];
6004 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6005 QualType VaListTagArrayType
6006 = Context->getConstantArrayType(VaListTagTypedefType,
6007 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006008 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006009}
6010
6011static TypedefDecl *
6012CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6013 // typedef struct __va_list_tag {
6014 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006015 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006016 VaListTagDecl->startDefinition();
6017
6018 const size_t NumFields = 4;
6019 QualType FieldTypes[NumFields];
6020 const char *FieldNames[NumFields];
6021
6022 // unsigned gp_offset;
6023 FieldTypes[0] = Context->UnsignedIntTy;
6024 FieldNames[0] = "gp_offset";
6025
6026 // unsigned fp_offset;
6027 FieldTypes[1] = Context->UnsignedIntTy;
6028 FieldNames[1] = "fp_offset";
6029
6030 // void* overflow_arg_area;
6031 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6032 FieldNames[2] = "overflow_arg_area";
6033
6034 // void* reg_save_area;
6035 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6036 FieldNames[3] = "reg_save_area";
6037
6038 // Create fields
6039 for (unsigned i = 0; i < NumFields; ++i) {
6040 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6041 VaListTagDecl,
6042 SourceLocation(),
6043 SourceLocation(),
6044 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006045 FieldTypes[i], /*TInfo=*/nullptr,
6046 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006047 /*Mutable=*/false,
6048 ICIS_NoInit);
6049 Field->setAccess(AS_public);
6050 VaListTagDecl->addDecl(Field);
6051 }
6052 VaListTagDecl->completeDefinition();
6053 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006054 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006055
6056 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006057 TypedefDecl *VaListTagTypedefDecl =
6058 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6059
Meador Inge5d3fb222012-06-16 03:34:49 +00006060 QualType VaListTagTypedefType =
6061 Context->getTypedefType(VaListTagTypedefDecl);
6062
6063 // typedef __va_list_tag __builtin_va_list[1];
6064 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6065 QualType VaListTagArrayType
6066 = Context->getConstantArrayType(VaListTagTypedefType,
6067 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006068 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006069}
6070
6071static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6072 // typedef int __builtin_va_list[4];
6073 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6074 QualType IntArrayType
6075 = Context->getConstantArrayType(Context->IntTy,
6076 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006077 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006078}
6079
Logan Chien57086ce2012-10-10 06:56:20 +00006080static TypedefDecl *
6081CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006082 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006083 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006084 if (Context->getLangOpts().CPlusPlus) {
6085 // namespace std { struct __va_list {
6086 NamespaceDecl *NS;
6087 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6088 Context->getTranslationUnitDecl(),
6089 /*Inline*/false, SourceLocation(),
6090 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006091 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006092 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006093 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006094 }
6095
6096 VaListDecl->startDefinition();
6097
6098 // void * __ap;
6099 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6100 VaListDecl,
6101 SourceLocation(),
6102 SourceLocation(),
6103 &Context->Idents.get("__ap"),
6104 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006105 /*TInfo=*/nullptr,
6106 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006107 /*Mutable=*/false,
6108 ICIS_NoInit);
6109 Field->setAccess(AS_public);
6110 VaListDecl->addDecl(Field);
6111
6112 // };
6113 VaListDecl->completeDefinition();
6114
6115 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006116 QualType T = Context->getRecordType(VaListDecl);
6117 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006118}
6119
Ulrich Weigand47445072013-05-06 16:26:41 +00006120static TypedefDecl *
6121CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6122 // typedef struct __va_list_tag {
6123 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006124 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006125 VaListTagDecl->startDefinition();
6126
6127 const size_t NumFields = 4;
6128 QualType FieldTypes[NumFields];
6129 const char *FieldNames[NumFields];
6130
6131 // long __gpr;
6132 FieldTypes[0] = Context->LongTy;
6133 FieldNames[0] = "__gpr";
6134
6135 // long __fpr;
6136 FieldTypes[1] = Context->LongTy;
6137 FieldNames[1] = "__fpr";
6138
6139 // void *__overflow_arg_area;
6140 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6141 FieldNames[2] = "__overflow_arg_area";
6142
6143 // void *__reg_save_area;
6144 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6145 FieldNames[3] = "__reg_save_area";
6146
6147 // Create fields
6148 for (unsigned i = 0; i < NumFields; ++i) {
6149 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6150 VaListTagDecl,
6151 SourceLocation(),
6152 SourceLocation(),
6153 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006154 FieldTypes[i], /*TInfo=*/nullptr,
6155 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006156 /*Mutable=*/false,
6157 ICIS_NoInit);
6158 Field->setAccess(AS_public);
6159 VaListTagDecl->addDecl(Field);
6160 }
6161 VaListTagDecl->completeDefinition();
6162 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6163 Context->VaListTagTy = VaListTagType;
6164
6165 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006166 TypedefDecl *VaListTagTypedefDecl =
6167 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006168 QualType VaListTagTypedefType =
6169 Context->getTypedefType(VaListTagTypedefDecl);
6170
6171 // typedef __va_list_tag __builtin_va_list[1];
6172 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6173 QualType VaListTagArrayType
6174 = Context->getConstantArrayType(VaListTagTypedefType,
6175 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006176
Alp Toker56b5cc92013-12-15 10:36:26 +00006177 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006178}
6179
Meador Inge5d3fb222012-06-16 03:34:49 +00006180static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6181 TargetInfo::BuiltinVaListKind Kind) {
6182 switch (Kind) {
6183 case TargetInfo::CharPtrBuiltinVaList:
6184 return CreateCharPtrBuiltinVaListDecl(Context);
6185 case TargetInfo::VoidPtrBuiltinVaList:
6186 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006187 case TargetInfo::AArch64ABIBuiltinVaList:
6188 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006189 case TargetInfo::PowerABIBuiltinVaList:
6190 return CreatePowerABIBuiltinVaListDecl(Context);
6191 case TargetInfo::X86_64ABIBuiltinVaList:
6192 return CreateX86_64ABIBuiltinVaListDecl(Context);
6193 case TargetInfo::PNaClABIBuiltinVaList:
6194 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006195 case TargetInfo::AAPCSABIBuiltinVaList:
6196 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006197 case TargetInfo::SystemZBuiltinVaList:
6198 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006199 }
6200
6201 llvm_unreachable("Unhandled __builtin_va_list type kind");
6202}
6203
6204TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006205 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006206 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006207 assert(BuiltinVaListDecl->isImplicit());
6208 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006209
6210 return BuiltinVaListDecl;
6211}
6212
Meador Ingecfb60902012-07-01 15:57:25 +00006213QualType ASTContext::getVaListTagType() const {
6214 // Force the creation of VaListTagTy by building the __builtin_va_list
6215 // declaration.
6216 if (VaListTagTy.isNull())
6217 (void) getBuiltinVaListDecl();
6218
6219 return VaListTagTy;
6220}
6221
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006222void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006223 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006224 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006225
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006226 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006227}
6228
John McCalld28ae272009-12-02 08:04:21 +00006229/// \brief Retrieve the template name that corresponds to a non-empty
6230/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006231TemplateName
6232ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6233 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006234 unsigned size = End - Begin;
6235 assert(size > 1 && "set is not overloaded!");
6236
6237 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6238 size * sizeof(FunctionTemplateDecl*));
6239 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6240
6241 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006242 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006243 NamedDecl *D = *I;
6244 assert(isa<FunctionTemplateDecl>(D) ||
6245 (isa<UsingShadowDecl>(D) &&
6246 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6247 *Storage++ = D;
6248 }
6249
6250 return TemplateName(OT);
6251}
6252
Douglas Gregordc572a32009-03-30 22:58:21 +00006253/// \brief Retrieve the template name that represents a qualified
6254/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006255TemplateName
6256ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6257 bool TemplateKeyword,
6258 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006259 assert(NNS && "Missing nested-name-specifier in qualified template name");
6260
Douglas Gregorc42075a2010-02-04 18:10:26 +00006261 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006262 llvm::FoldingSetNodeID ID;
6263 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6264
Craig Topper36250ad2014-05-12 05:36:57 +00006265 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006266 QualifiedTemplateName *QTN =
6267 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6268 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006269 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6270 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006271 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6272 }
6273
6274 return TemplateName(QTN);
6275}
6276
6277/// \brief Retrieve the template name that represents a dependent
6278/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006279TemplateName
6280ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6281 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006282 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006283 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006284
6285 llvm::FoldingSetNodeID ID;
6286 DependentTemplateName::Profile(ID, NNS, Name);
6287
Craig Topper36250ad2014-05-12 05:36:57 +00006288 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006289 DependentTemplateName *QTN =
6290 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6291
6292 if (QTN)
6293 return TemplateName(QTN);
6294
6295 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6296 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006297 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6298 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006299 } else {
6300 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006301 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6302 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006303 DependentTemplateName *CheckQTN =
6304 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6305 assert(!CheckQTN && "Dependent type name canonicalization broken");
6306 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006307 }
6308
6309 DependentTemplateNames.InsertNode(QTN, InsertPos);
6310 return TemplateName(QTN);
6311}
6312
Douglas Gregor71395fa2009-11-04 00:56:37 +00006313/// \brief Retrieve the template name that represents a dependent
6314/// template name such as \c MetaFun::template operator+.
6315TemplateName
6316ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006317 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006318 assert((!NNS || NNS->isDependent()) &&
6319 "Nested name specifier must be dependent");
6320
6321 llvm::FoldingSetNodeID ID;
6322 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006323
6324 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006325 DependentTemplateName *QTN
6326 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006327
6328 if (QTN)
6329 return TemplateName(QTN);
6330
6331 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6332 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006333 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6334 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006335 } else {
6336 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006337 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6338 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006339
6340 DependentTemplateName *CheckQTN
6341 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6342 assert(!CheckQTN && "Dependent template name canonicalization broken");
6343 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006344 }
6345
6346 DependentTemplateNames.InsertNode(QTN, InsertPos);
6347 return TemplateName(QTN);
6348}
6349
Douglas Gregor5590be02011-01-15 06:45:20 +00006350TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006351ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6352 TemplateName replacement) const {
6353 llvm::FoldingSetNodeID ID;
6354 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006355
6356 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006357 SubstTemplateTemplateParmStorage *subst
6358 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6359
6360 if (!subst) {
6361 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6362 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6363 }
6364
6365 return TemplateName(subst);
6366}
6367
6368TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006369ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6370 const TemplateArgument &ArgPack) const {
6371 ASTContext &Self = const_cast<ASTContext &>(*this);
6372 llvm::FoldingSetNodeID ID;
6373 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006374
6375 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006376 SubstTemplateTemplateParmPackStorage *Subst
6377 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6378
6379 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006380 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006381 ArgPack.pack_size(),
6382 ArgPack.pack_begin());
6383 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6384 }
6385
6386 return TemplateName(Subst);
6387}
6388
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006389/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006390/// TargetInfo, produce the corresponding type. The unsigned @p Type
6391/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006392CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006393 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006394 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006395 case TargetInfo::SignedChar: return SignedCharTy;
6396 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006397 case TargetInfo::SignedShort: return ShortTy;
6398 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6399 case TargetInfo::SignedInt: return IntTy;
6400 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6401 case TargetInfo::SignedLong: return LongTy;
6402 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6403 case TargetInfo::SignedLongLong: return LongLongTy;
6404 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6405 }
6406
David Blaikie83d382b2011-09-23 05:06:16 +00006407 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006408}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006409
6410//===----------------------------------------------------------------------===//
6411// Type Predicates.
6412//===----------------------------------------------------------------------===//
6413
Fariborz Jahanian96207692009-02-18 21:49:28 +00006414/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6415/// garbage collection attribute.
6416///
John McCall553d45a2011-01-12 00:34:59 +00006417Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006418 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006419 return Qualifiers::GCNone;
6420
David Blaikiebbafb8a2012-03-11 07:00:24 +00006421 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006422 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6423
6424 // Default behaviour under objective-C's gc is for ObjC pointers
6425 // (or pointers to them) be treated as though they were declared
6426 // as __strong.
6427 if (GCAttrs == Qualifiers::GCNone) {
6428 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6429 return Qualifiers::Strong;
6430 else if (Ty->isPointerType())
6431 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6432 } else {
6433 // It's not valid to set GC attributes on anything that isn't a
6434 // pointer.
6435#ifndef NDEBUG
6436 QualType CT = Ty->getCanonicalTypeInternal();
6437 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6438 CT = AT->getElementType();
6439 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6440#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006441 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006442 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006443}
6444
Chris Lattner49af6a42008-04-07 06:51:04 +00006445//===----------------------------------------------------------------------===//
6446// Type Compatibility Testing
6447//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006448
Mike Stump11289f42009-09-09 15:08:12 +00006449/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006450/// compatible.
6451static bool areCompatVectorTypes(const VectorType *LHS,
6452 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006453 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006454 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006455 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006456}
6457
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006458bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6459 QualType SecondVec) {
6460 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6461 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6462
6463 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6464 return true;
6465
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006466 // Treat Neon vector types and most AltiVec vector types as if they are the
6467 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006468 const VectorType *First = FirstVec->getAs<VectorType>();
6469 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006470 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006471 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006472 First->getVectorKind() != VectorType::AltiVecPixel &&
6473 First->getVectorKind() != VectorType::AltiVecBool &&
6474 Second->getVectorKind() != VectorType::AltiVecPixel &&
6475 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006476 return true;
6477
6478 return false;
6479}
6480
Steve Naroff8e6aee52009-07-23 01:01:38 +00006481//===----------------------------------------------------------------------===//
6482// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6483//===----------------------------------------------------------------------===//
6484
6485/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6486/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006487bool
6488ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6489 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006490 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006491 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006492 for (auto *PI : rProto->protocols())
6493 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006494 return true;
6495 return false;
6496}
6497
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006498/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6499/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006500bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6501 QualType rhs) {
6502 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6503 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6504 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6505
Aaron Ballman83731462014-03-17 16:14:00 +00006506 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006507 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006508 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006509 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6510 match = true;
6511 break;
6512 }
6513 }
6514 if (!match)
6515 return false;
6516 }
6517 return true;
6518}
6519
Steve Naroff8e6aee52009-07-23 01:01:38 +00006520/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6521/// ObjCQualifiedIDType.
6522bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6523 bool compare) {
6524 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006525 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006526 lhs->isObjCIdType() || lhs->isObjCClassType())
6527 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006528 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006529 rhs->isObjCIdType() || rhs->isObjCClassType())
6530 return true;
6531
6532 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006533 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006534
Steve Naroff8e6aee52009-07-23 01:01:38 +00006535 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006536
Steve Naroff8e6aee52009-07-23 01:01:38 +00006537 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006538 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006539 // make sure we check the class hierarchy.
6540 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006541 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006542 // when comparing an id<P> on lhs with a static type on rhs,
6543 // see if static class implements all of id's protocols, directly or
6544 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006545 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006546 return false;
6547 }
6548 }
6549 // If there are no qualifiers and no interface, we have an 'id'.
6550 return true;
6551 }
Mike Stump11289f42009-09-09 15:08:12 +00006552 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006553 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006554 bool match = false;
6555
6556 // when comparing an id<P> on lhs with a static type on rhs,
6557 // see if static class implements all of id's protocols, directly or
6558 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006559 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006560 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6561 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6562 match = true;
6563 break;
6564 }
6565 }
Mike Stump11289f42009-09-09 15:08:12 +00006566 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006567 // make sure we check the class hierarchy.
6568 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006569 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006570 // when comparing an id<P> on lhs with a static type on rhs,
6571 // see if static class implements all of id's protocols, directly or
6572 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006573 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006574 match = true;
6575 break;
6576 }
6577 }
6578 }
6579 if (!match)
6580 return false;
6581 }
Mike Stump11289f42009-09-09 15:08:12 +00006582
Steve Naroff8e6aee52009-07-23 01:01:38 +00006583 return true;
6584 }
Mike Stump11289f42009-09-09 15:08:12 +00006585
Steve Naroff8e6aee52009-07-23 01:01:38 +00006586 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6587 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6588
Mike Stump11289f42009-09-09 15:08:12 +00006589 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006590 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006591 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006592 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006593 bool match = false;
6594
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006595 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006596 // see if static class implements all of id's protocols, directly or
6597 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006598 // First, lhs protocols in the qualifier list must be found, direct
6599 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006600 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006601 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6602 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6603 match = true;
6604 break;
6605 }
6606 }
6607 if (!match)
6608 return false;
6609 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006610
6611 // Static class's protocols, or its super class or category protocols
6612 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6613 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6614 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6615 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6616 // This is rather dubious but matches gcc's behavior. If lhs has
6617 // no type qualifier and its class has no static protocol(s)
6618 // assume that it is mismatch.
6619 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6620 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006621 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006622 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006623 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006624 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6625 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6626 match = true;
6627 break;
6628 }
6629 }
6630 if (!match)
6631 return false;
6632 }
6633 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006634 return true;
6635 }
6636 return false;
6637}
6638
Eli Friedman47f77112008-08-22 00:56:42 +00006639/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006640/// compatible for assignment from RHS to LHS. This handles validation of any
6641/// protocol qualifiers on the LHS or RHS.
6642///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006643bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6644 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006645 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6646 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6647
Steve Naroff1329fa02009-07-15 18:40:39 +00006648 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006649 if (LHS->isObjCUnqualifiedIdOrClass() ||
6650 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006651 return true;
6652
John McCall8b07ec22010-05-15 11:32:37 +00006653 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006654 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6655 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006656 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006657
6658 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6659 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6660 QualType(RHSOPT,0));
6661
John McCall8b07ec22010-05-15 11:32:37 +00006662 // If we have 2 user-defined types, fall into that path.
6663 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006664 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006665
Steve Naroff8e6aee52009-07-23 01:01:38 +00006666 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006667}
6668
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006669/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006670/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006671/// arguments in block literals. When passed as arguments, passing 'A*' where
6672/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6673/// not OK. For the return type, the opposite is not OK.
6674bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6675 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006676 const ObjCObjectPointerType *RHSOPT,
6677 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006678 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006679 return true;
6680
6681 if (LHSOPT->isObjCBuiltinType()) {
6682 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6683 }
6684
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006685 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006686 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6687 QualType(RHSOPT,0),
6688 false);
6689
6690 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6691 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6692 if (LHS && RHS) { // We have 2 user-defined types.
6693 if (LHS != RHS) {
6694 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006695 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006696 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006697 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006698 }
6699 else
6700 return true;
6701 }
6702 return false;
6703}
6704
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006705/// getIntersectionOfProtocols - This routine finds the intersection of set
6706/// of protocols inherited from two distinct objective-c pointer objects.
6707/// It is used to build composite qualifier list of the composite type of
6708/// the conditional expression involving two objective-c pointer objects.
6709static
6710void getIntersectionOfProtocols(ASTContext &Context,
6711 const ObjCObjectPointerType *LHSOPT,
6712 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006713 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006714
John McCall8b07ec22010-05-15 11:32:37 +00006715 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6716 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6717 assert(LHS->getInterface() && "LHS must have an interface base");
6718 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006719
6720 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6721 unsigned LHSNumProtocols = LHS->getNumProtocols();
6722 if (LHSNumProtocols > 0)
6723 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6724 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006725 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006726 Context.CollectInheritedProtocols(LHS->getInterface(),
6727 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006728 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6729 LHSInheritedProtocols.end());
6730 }
6731
6732 unsigned RHSNumProtocols = RHS->getNumProtocols();
6733 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006734 ObjCProtocolDecl **RHSProtocols =
6735 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006736 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6737 if (InheritedProtocolSet.count(RHSProtocols[i]))
6738 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006739 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006740 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006741 Context.CollectInheritedProtocols(RHS->getInterface(),
6742 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006743 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6744 if (InheritedProtocolSet.count(ProtDecl))
6745 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006746 }
6747}
6748
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006749/// areCommonBaseCompatible - Returns common base class of the two classes if
6750/// one found. Note that this is O'2 algorithm. But it will be called as the
6751/// last type comparison in a ?-exp of ObjC pointer types before a
6752/// warning is issued. So, its invokation is extremely rare.
6753QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006754 const ObjCObjectPointerType *Lptr,
6755 const ObjCObjectPointerType *Rptr) {
6756 const ObjCObjectType *LHS = Lptr->getObjectType();
6757 const ObjCObjectType *RHS = Rptr->getObjectType();
6758 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6759 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006760 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006761 return QualType();
6762
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006763 do {
John McCall8b07ec22010-05-15 11:32:37 +00006764 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006765 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006766 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006767 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6768
6769 QualType Result = QualType(LHS, 0);
6770 if (!Protocols.empty())
6771 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6772 Result = getObjCObjectPointerType(Result);
6773 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006774 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006775 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006776
6777 return QualType();
6778}
6779
John McCall8b07ec22010-05-15 11:32:37 +00006780bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6781 const ObjCObjectType *RHS) {
6782 assert(LHS->getInterface() && "LHS is not an interface type");
6783 assert(RHS->getInterface() && "RHS is not an interface type");
6784
Chris Lattner49af6a42008-04-07 06:51:04 +00006785 // Verify that the base decls are compatible: the RHS must be a subclass of
6786 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006787 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006788 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006789
Chris Lattner49af6a42008-04-07 06:51:04 +00006790 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6791 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006792 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006793 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006794
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006795 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6796 // More detailed analysis is required.
6797 // OK, if LHS is same or a superclass of RHS *and*
6798 // this LHS, or as RHS's super class is assignment compatible with LHS.
6799 bool IsSuperClass =
6800 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6801 if (IsSuperClass) {
6802 // OK if conversion of LHS to SuperClass results in narrowing of types
6803 // ; i.e., SuperClass may implement at least one of the protocols
6804 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6805 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6806 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6807 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6808 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6809 // qualifiers.
6810 for (auto *RHSPI : RHS->quals())
6811 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6812 // If there is no protocols associated with RHS, it is not a match.
6813 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006814 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006815
6816 for (const auto *LHSProto : LHS->quals()) {
6817 bool SuperImplementsProtocol = false;
6818 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6819 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6820 SuperImplementsProtocol = true;
6821 break;
6822 }
6823 if (!SuperImplementsProtocol)
6824 return false;
6825 }
6826 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006827 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006828 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006829}
6830
Steve Naroffb7605152009-02-12 17:52:19 +00006831bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6832 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006833 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6834 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006835
Steve Naroff7cae42b2009-07-10 23:34:53 +00006836 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006837 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006838
6839 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6840 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006841}
6842
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006843bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6844 return canAssignObjCInterfaces(
6845 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6846 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6847}
6848
Mike Stump11289f42009-09-09 15:08:12 +00006849/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006850/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006851/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006852/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006853bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6854 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006855 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006856 return hasSameType(LHS, RHS);
6857
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006858 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006859}
6860
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006861bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006862 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006863}
6864
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006865bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6866 return !mergeTypes(LHS, RHS, true).isNull();
6867}
6868
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006869/// mergeTransparentUnionType - if T is a transparent union type and a member
6870/// of T is compatible with SubType, return the merged type, else return
6871/// QualType()
6872QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6873 bool OfBlockPointer,
6874 bool Unqualified) {
6875 if (const RecordType *UT = T->getAsUnionType()) {
6876 RecordDecl *UD = UT->getDecl();
6877 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006878 for (const auto *I : UD->fields()) {
6879 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006880 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6881 if (!MT.isNull())
6882 return MT;
6883 }
6884 }
6885 }
6886
6887 return QualType();
6888}
6889
Alp Toker9cacbab2014-01-20 20:26:09 +00006890/// mergeFunctionParameterTypes - merge two types which appear as function
6891/// parameter types
6892QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6893 bool OfBlockPointer,
6894 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006895 // GNU extension: two types are compatible if they appear as a function
6896 // argument, one of the types is a transparent union type and the other
6897 // type is compatible with a union member
6898 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6899 Unqualified);
6900 if (!lmerge.isNull())
6901 return lmerge;
6902
6903 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6904 Unqualified);
6905 if (!rmerge.isNull())
6906 return rmerge;
6907
6908 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6909}
6910
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006911QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006912 bool OfBlockPointer,
6913 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006914 const FunctionType *lbase = lhs->getAs<FunctionType>();
6915 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006916 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6917 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006918 bool allLTypes = true;
6919 bool allRTypes = true;
6920
6921 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006922 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006923 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006924 QualType RHS = rbase->getReturnType();
6925 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006926 bool UnqualifiedResult = Unqualified;
6927 if (!UnqualifiedResult)
6928 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006929 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006930 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006931 else
Alp Toker314cc812014-01-25 16:55:45 +00006932 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006933 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006934 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006935
6936 if (Unqualified)
6937 retType = retType.getUnqualifiedType();
6938
Alp Toker314cc812014-01-25 16:55:45 +00006939 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6940 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006941 if (Unqualified) {
6942 LRetType = LRetType.getUnqualifiedType();
6943 RRetType = RRetType.getUnqualifiedType();
6944 }
6945
6946 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006947 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006948 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006949 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006950
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006951 // FIXME: double check this
6952 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6953 // rbase->getRegParmAttr() != 0 &&
6954 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006955 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6956 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006957
Douglas Gregor8c940862010-01-18 17:14:39 +00006958 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006959 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006960 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006961
John McCall8c6b56f2010-12-15 01:06:38 +00006962 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006963 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6964 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006965 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6966 return QualType();
6967
John McCall31168b02011-06-15 23:02:42 +00006968 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6969 return QualType();
6970
John McCall8c6b56f2010-12-15 01:06:38 +00006971 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6972 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006973
Rafael Espindola8778c282012-11-29 16:09:03 +00006974 if (lbaseInfo.getNoReturn() != NoReturn)
6975 allLTypes = false;
6976 if (rbaseInfo.getNoReturn() != NoReturn)
6977 allRTypes = false;
6978
John McCall31168b02011-06-15 23:02:42 +00006979 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006980
Eli Friedman47f77112008-08-22 00:56:42 +00006981 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006982 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6983 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006984 // Compatible functions must have the same number of parameters
6985 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006986 return QualType();
6987
6988 // Variadic and non-variadic functions aren't compatible
6989 if (lproto->isVariadic() != rproto->isVariadic())
6990 return QualType();
6991
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006992 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6993 return QualType();
6994
Fariborz Jahanian97676972011-09-28 21:52:05 +00006995 if (LangOpts.ObjCAutoRefCount &&
6996 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6997 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006998
6999 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007000 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007001 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7002 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7003 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7004 QualType paramType = mergeFunctionParameterTypes(
7005 lParamType, rParamType, OfBlockPointer, Unqualified);
7006 if (paramType.isNull())
7007 return QualType();
7008
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007009 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007010 paramType = paramType.getUnqualifiedType();
7011
7012 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007013 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007014 lParamType = lParamType.getUnqualifiedType();
7015 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007016 }
Alp Toker601b22c2014-01-21 23:35:24 +00007017
7018 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007019 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007020 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007021 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007022 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007023
Eli Friedman47f77112008-08-22 00:56:42 +00007024 if (allLTypes) return lhs;
7025 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007026
7027 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7028 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007029 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007030 }
7031
7032 if (lproto) allRTypes = false;
7033 if (rproto) allLTypes = false;
7034
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007035 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007036 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007037 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007038 if (proto->isVariadic()) return QualType();
7039 // Check that the types are compatible with the types that
7040 // would result from default argument promotions (C99 6.7.5.3p15).
7041 // The only types actually affected are promotable integer
7042 // types and floats, which would be passed as a different
7043 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007044 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7045 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007046
Eli Friedman448ce402012-08-30 00:44:15 +00007047 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007048 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007049 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7050 paramTy = Enum->getDecl()->getIntegerType();
7051 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007052 return QualType();
7053 }
Alp Toker601b22c2014-01-21 23:35:24 +00007054
7055 if (paramTy->isPromotableIntegerType() ||
7056 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007057 return QualType();
7058 }
7059
7060 if (allLTypes) return lhs;
7061 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007062
7063 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7064 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007065 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007066 }
7067
7068 if (allLTypes) return lhs;
7069 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007070 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007071}
7072
John McCall433c2e62013-03-21 00:10:07 +00007073/// Given that we have an enum type and a non-enum type, try to merge them.
7074static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7075 QualType other, bool isBlockReturnType) {
7076 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7077 // a signed integer type, or an unsigned integer type.
7078 // Compatibility is based on the underlying type, not the promotion
7079 // type.
7080 QualType underlyingType = ET->getDecl()->getIntegerType();
7081 if (underlyingType.isNull()) return QualType();
7082 if (Context.hasSameType(underlyingType, other))
7083 return other;
7084
7085 // In block return types, we're more permissive and accept any
7086 // integral type of the same size.
7087 if (isBlockReturnType && other->isIntegerType() &&
7088 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7089 return other;
7090
7091 return QualType();
7092}
7093
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007094QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007095 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007096 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007097 // C++ [expr]: If an expression initially has the type "reference to T", the
7098 // type is adjusted to "T" prior to any further analysis, the expression
7099 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007100 // expression is an lvalue unless the reference is an rvalue reference and
7101 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007102 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7103 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007104
7105 if (Unqualified) {
7106 LHS = LHS.getUnqualifiedType();
7107 RHS = RHS.getUnqualifiedType();
7108 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007109
Eli Friedman47f77112008-08-22 00:56:42 +00007110 QualType LHSCan = getCanonicalType(LHS),
7111 RHSCan = getCanonicalType(RHS);
7112
7113 // If two types are identical, they are compatible.
7114 if (LHSCan == RHSCan)
7115 return LHS;
7116
John McCall8ccfcb52009-09-24 19:53:00 +00007117 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007118 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7119 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007120 if (LQuals != RQuals) {
7121 // If any of these qualifiers are different, we have a type
7122 // mismatch.
7123 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007124 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7125 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007126 return QualType();
7127
7128 // Exactly one GC qualifier difference is allowed: __strong is
7129 // okay if the other type has no GC qualifier but is an Objective
7130 // C object pointer (i.e. implicitly strong by default). We fix
7131 // this by pretending that the unqualified type was actually
7132 // qualified __strong.
7133 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7134 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7135 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7136
7137 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7138 return QualType();
7139
7140 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7141 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7142 }
7143 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7144 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7145 }
Eli Friedman47f77112008-08-22 00:56:42 +00007146 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007147 }
7148
7149 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007150
Eli Friedmandcca6332009-06-01 01:22:52 +00007151 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7152 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007153
Chris Lattnerfd652912008-01-14 05:45:46 +00007154 // We want to consider the two function types to be the same for these
7155 // comparisons, just force one to the other.
7156 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7157 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007158
7159 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007160 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7161 LHSClass = Type::ConstantArray;
7162 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7163 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007164
John McCall8b07ec22010-05-15 11:32:37 +00007165 // ObjCInterfaces are just specialized ObjCObjects.
7166 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7167 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7168
Nate Begemance4d7fc2008-04-18 23:10:10 +00007169 // Canonicalize ExtVector -> Vector.
7170 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7171 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007172
Chris Lattner95554662008-04-07 05:43:21 +00007173 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007174 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007175 // Note that we only have special rules for turning block enum
7176 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007177 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007178 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007179 }
John McCall9dd450b2009-09-21 23:43:11 +00007180 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007181 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007182 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007183 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007184 if (OfBlockPointer && !BlockReturnType) {
7185 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7186 return LHS;
7187 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7188 return RHS;
7189 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007190
Eli Friedman47f77112008-08-22 00:56:42 +00007191 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007192 }
Eli Friedman47f77112008-08-22 00:56:42 +00007193
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007194 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007195 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007196#define TYPE(Class, Base)
7197#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007198#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007199#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7200#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7201#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007202 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007203
Richard Smith27d807c2013-04-30 13:56:41 +00007204 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007205 case Type::LValueReference:
7206 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007207 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007208 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007209
John McCall8b07ec22010-05-15 11:32:37 +00007210 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007211 case Type::IncompleteArray:
7212 case Type::VariableArray:
7213 case Type::FunctionProto:
7214 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007215 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007216
Chris Lattnerfd652912008-01-14 05:45:46 +00007217 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007218 {
7219 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007220 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7221 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007222 if (Unqualified) {
7223 LHSPointee = LHSPointee.getUnqualifiedType();
7224 RHSPointee = RHSPointee.getUnqualifiedType();
7225 }
7226 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7227 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007228 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007229 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007230 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007231 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007232 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007233 return getPointerType(ResultType);
7234 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007235 case Type::BlockPointer:
7236 {
7237 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007238 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7239 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007240 if (Unqualified) {
7241 LHSPointee = LHSPointee.getUnqualifiedType();
7242 RHSPointee = RHSPointee.getUnqualifiedType();
7243 }
7244 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7245 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007246 if (ResultType.isNull()) return QualType();
7247 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7248 return LHS;
7249 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7250 return RHS;
7251 return getBlockPointerType(ResultType);
7252 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007253 case Type::Atomic:
7254 {
7255 // Merge two pointer types, while trying to preserve typedef info
7256 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7257 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7258 if (Unqualified) {
7259 LHSValue = LHSValue.getUnqualifiedType();
7260 RHSValue = RHSValue.getUnqualifiedType();
7261 }
7262 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7263 Unqualified);
7264 if (ResultType.isNull()) return QualType();
7265 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7266 return LHS;
7267 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7268 return RHS;
7269 return getAtomicType(ResultType);
7270 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007271 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007272 {
7273 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7274 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7275 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7276 return QualType();
7277
7278 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7279 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007280 if (Unqualified) {
7281 LHSElem = LHSElem.getUnqualifiedType();
7282 RHSElem = RHSElem.getUnqualifiedType();
7283 }
7284
7285 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007286 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007287 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7288 return LHS;
7289 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7290 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007291 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7292 ArrayType::ArraySizeModifier(), 0);
7293 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7294 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007295 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7296 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007297 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7298 return LHS;
7299 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7300 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007301 if (LVAT) {
7302 // FIXME: This isn't correct! But tricky to implement because
7303 // the array's size has to be the size of LHS, but the type
7304 // has to be different.
7305 return LHS;
7306 }
7307 if (RVAT) {
7308 // FIXME: This isn't correct! But tricky to implement because
7309 // the array's size has to be the size of RHS, but the type
7310 // has to be different.
7311 return RHS;
7312 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007313 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7314 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007315 return getIncompleteArrayType(ResultType,
7316 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007317 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007318 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007319 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007320 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007321 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007322 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007323 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007324 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007325 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007326 case Type::Complex:
7327 // Distinct complex types are incompatible.
7328 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007329 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007330 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007331 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7332 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007333 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007334 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007335 case Type::ObjCObject: {
7336 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007337 // FIXME: This should be type compatibility, e.g. whether
7338 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007339 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7340 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7341 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007342 return LHS;
7343
Eli Friedman47f77112008-08-22 00:56:42 +00007344 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007345 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007346 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007347 if (OfBlockPointer) {
7348 if (canAssignObjCInterfacesInBlockPointer(
7349 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007350 RHS->getAs<ObjCObjectPointerType>(),
7351 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007352 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007353 return QualType();
7354 }
John McCall9dd450b2009-09-21 23:43:11 +00007355 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7356 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007357 return LHS;
7358
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007359 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007360 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007361 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007362
David Blaikie8a40f702012-01-17 06:56:22 +00007363 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007364}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007365
Fariborz Jahanian97676972011-09-28 21:52:05 +00007366bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7367 const FunctionProtoType *FromFunctionType,
7368 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007369 if (FromFunctionType->hasAnyConsumedParams() !=
7370 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007371 return false;
7372 FunctionProtoType::ExtProtoInfo FromEPI =
7373 FromFunctionType->getExtProtoInfo();
7374 FunctionProtoType::ExtProtoInfo ToEPI =
7375 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007376 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007377 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7378 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007379 return false;
7380 }
7381 return true;
7382}
7383
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007384/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7385/// 'RHS' attributes and returns the merged version; including for function
7386/// return types.
7387QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7388 QualType LHSCan = getCanonicalType(LHS),
7389 RHSCan = getCanonicalType(RHS);
7390 // If two types are identical, they are compatible.
7391 if (LHSCan == RHSCan)
7392 return LHS;
7393 if (RHSCan->isFunctionType()) {
7394 if (!LHSCan->isFunctionType())
7395 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007396 QualType OldReturnType =
7397 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007398 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007399 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007400 QualType ResReturnType =
7401 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7402 if (ResReturnType.isNull())
7403 return QualType();
7404 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7405 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7406 // In either case, use OldReturnType to build the new function type.
7407 const FunctionType *F = LHS->getAs<FunctionType>();
7408 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007409 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7410 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007411 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007412 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007413 return ResultType;
7414 }
7415 }
7416 return QualType();
7417 }
7418
7419 // If the qualifiers are different, the types can still be merged.
7420 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7421 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7422 if (LQuals != RQuals) {
7423 // If any of these qualifiers are different, we have a type mismatch.
7424 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7425 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7426 return QualType();
7427
7428 // Exactly one GC qualifier difference is allowed: __strong is
7429 // okay if the other type has no GC qualifier but is an Objective
7430 // C object pointer (i.e. implicitly strong by default). We fix
7431 // this by pretending that the unqualified type was actually
7432 // qualified __strong.
7433 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7434 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7435 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7436
7437 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7438 return QualType();
7439
7440 if (GC_L == Qualifiers::Strong)
7441 return LHS;
7442 if (GC_R == Qualifiers::Strong)
7443 return RHS;
7444 return QualType();
7445 }
7446
7447 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7448 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7449 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7450 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7451 if (ResQT == LHSBaseQT)
7452 return LHS;
7453 if (ResQT == RHSBaseQT)
7454 return RHS;
7455 }
7456 return QualType();
7457}
7458
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007459//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007460// Integer Predicates
7461//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007462
Jay Foad39c79802011-01-12 09:06:06 +00007463unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007464 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007465 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007466 if (T->isBooleanType())
7467 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007468 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007469 return (unsigned)getTypeSize(T);
7470}
7471
Abramo Bagnara13640492012-09-09 10:21:24 +00007472QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007473 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007474
7475 // Turn <4 x signed int> -> <4 x unsigned int>
7476 if (const VectorType *VTy = T->getAs<VectorType>())
7477 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007478 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007479
7480 // For enums, we return the unsigned version of the base type.
7481 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007482 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007483
7484 const BuiltinType *BTy = T->getAs<BuiltinType>();
7485 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007486 switch (BTy->getKind()) {
7487 case BuiltinType::Char_S:
7488 case BuiltinType::SChar:
7489 return UnsignedCharTy;
7490 case BuiltinType::Short:
7491 return UnsignedShortTy;
7492 case BuiltinType::Int:
7493 return UnsignedIntTy;
7494 case BuiltinType::Long:
7495 return UnsignedLongTy;
7496 case BuiltinType::LongLong:
7497 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007498 case BuiltinType::Int128:
7499 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007500 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007501 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007502 }
7503}
7504
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007505ASTMutationListener::~ASTMutationListener() { }
7506
Richard Smith1fa5d642013-05-11 05:45:24 +00007507void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7508 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007509
7510//===----------------------------------------------------------------------===//
7511// Builtin Type Computation
7512//===----------------------------------------------------------------------===//
7513
7514/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007515/// pointer over the consumed characters. This returns the resultant type. If
7516/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7517/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7518/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007519///
7520/// RequiresICE is filled in on return to indicate whether the value is required
7521/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007522static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007523 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007524 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007525 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007526 // Modifiers.
7527 int HowLong = 0;
7528 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007529 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007530
Chris Lattnerdc226c22010-10-01 22:42:38 +00007531 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007532 bool Done = false;
7533 while (!Done) {
7534 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007535 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007536 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007537 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007538 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007539 case 'S':
7540 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7541 assert(!Signed && "Can't use 'S' modifier multiple times!");
7542 Signed = true;
7543 break;
7544 case 'U':
7545 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7546 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7547 Unsigned = true;
7548 break;
7549 case 'L':
7550 assert(HowLong <= 2 && "Can't have LLLL modifier");
7551 ++HowLong;
7552 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007553 case 'W':
7554 // This modifier represents int64 type.
7555 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7556 switch (Context.getTargetInfo().getInt64Type()) {
7557 default:
7558 llvm_unreachable("Unexpected integer type");
7559 case TargetInfo::SignedLong:
7560 HowLong = 1;
7561 break;
7562 case TargetInfo::SignedLongLong:
7563 HowLong = 2;
7564 break;
7565 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007566 }
7567 }
7568
7569 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007570
Chris Lattnerecd79c62009-06-14 00:45:47 +00007571 // Read the base type.
7572 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007573 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007574 case 'v':
7575 assert(HowLong == 0 && !Signed && !Unsigned &&
7576 "Bad modifiers used with 'v'!");
7577 Type = Context.VoidTy;
7578 break;
Jack Carter24bef982013-08-15 15:16:57 +00007579 case 'h':
7580 assert(HowLong == 0 && !Signed && !Unsigned &&
7581 "Bad modifiers used with 'f'!");
7582 Type = Context.HalfTy;
7583 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007584 case 'f':
7585 assert(HowLong == 0 && !Signed && !Unsigned &&
7586 "Bad modifiers used with 'f'!");
7587 Type = Context.FloatTy;
7588 break;
7589 case 'd':
7590 assert(HowLong < 2 && !Signed && !Unsigned &&
7591 "Bad modifiers used with 'd'!");
7592 if (HowLong)
7593 Type = Context.LongDoubleTy;
7594 else
7595 Type = Context.DoubleTy;
7596 break;
7597 case 's':
7598 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7599 if (Unsigned)
7600 Type = Context.UnsignedShortTy;
7601 else
7602 Type = Context.ShortTy;
7603 break;
7604 case 'i':
7605 if (HowLong == 3)
7606 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7607 else if (HowLong == 2)
7608 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7609 else if (HowLong == 1)
7610 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7611 else
7612 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7613 break;
7614 case 'c':
7615 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7616 if (Signed)
7617 Type = Context.SignedCharTy;
7618 else if (Unsigned)
7619 Type = Context.UnsignedCharTy;
7620 else
7621 Type = Context.CharTy;
7622 break;
7623 case 'b': // boolean
7624 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7625 Type = Context.BoolTy;
7626 break;
7627 case 'z': // size_t.
7628 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7629 Type = Context.getSizeType();
7630 break;
7631 case 'F':
7632 Type = Context.getCFConstantStringType();
7633 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007634 case 'G':
7635 Type = Context.getObjCIdType();
7636 break;
7637 case 'H':
7638 Type = Context.getObjCSelType();
7639 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007640 case 'M':
7641 Type = Context.getObjCSuperType();
7642 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007643 case 'a':
7644 Type = Context.getBuiltinVaListType();
7645 assert(!Type.isNull() && "builtin va list type not initialized!");
7646 break;
7647 case 'A':
7648 // This is a "reference" to a va_list; however, what exactly
7649 // this means depends on how va_list is defined. There are two
7650 // different kinds of va_list: ones passed by value, and ones
7651 // passed by reference. An example of a by-value va_list is
7652 // x86, where va_list is a char*. An example of by-ref va_list
7653 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7654 // we want this argument to be a char*&; for x86-64, we want
7655 // it to be a __va_list_tag*.
7656 Type = Context.getBuiltinVaListType();
7657 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007658 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007659 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007660 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007661 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007662 break;
7663 case 'V': {
7664 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007665 unsigned NumElements = strtoul(Str, &End, 10);
7666 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007667 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007668
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007669 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7670 RequiresICE, false);
7671 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007672
7673 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007674 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007675 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007676 break;
7677 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007678 case 'E': {
7679 char *End;
7680
7681 unsigned NumElements = strtoul(Str, &End, 10);
7682 assert(End != Str && "Missing vector size");
7683
7684 Str = End;
7685
7686 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7687 false);
7688 Type = Context.getExtVectorType(ElementType, NumElements);
7689 break;
7690 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007691 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007692 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7693 false);
7694 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007695 Type = Context.getComplexType(ElementType);
7696 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007697 }
7698 case 'Y' : {
7699 Type = Context.getPointerDiffType();
7700 break;
7701 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007702 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007703 Type = Context.getFILEType();
7704 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007705 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007706 return QualType();
7707 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007708 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007709 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007710 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007711 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007712 else
7713 Type = Context.getjmp_bufType();
7714
Mike Stump2adb4da2009-07-28 23:47:15 +00007715 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007716 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007717 return QualType();
7718 }
7719 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007720 case 'K':
7721 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7722 Type = Context.getucontext_tType();
7723
7724 if (Type.isNull()) {
7725 Error = ASTContext::GE_Missing_ucontext;
7726 return QualType();
7727 }
7728 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007729 case 'p':
7730 Type = Context.getProcessIDType();
7731 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007732 }
Mike Stump11289f42009-09-09 15:08:12 +00007733
Chris Lattnerdc226c22010-10-01 22:42:38 +00007734 // If there are modifiers and if we're allowed to parse them, go for it.
7735 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007736 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007737 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007738 default: Done = true; --Str; break;
7739 case '*':
7740 case '&': {
7741 // Both pointers and references can have their pointee types
7742 // qualified with an address space.
7743 char *End;
7744 unsigned AddrSpace = strtoul(Str, &End, 10);
7745 if (End != Str && AddrSpace != 0) {
7746 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7747 Str = End;
7748 }
7749 if (c == '*')
7750 Type = Context.getPointerType(Type);
7751 else
7752 Type = Context.getLValueReferenceType(Type);
7753 break;
7754 }
7755 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7756 case 'C':
7757 Type = Type.withConst();
7758 break;
7759 case 'D':
7760 Type = Context.getVolatileType(Type);
7761 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007762 case 'R':
7763 Type = Type.withRestrict();
7764 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007765 }
7766 }
Chris Lattner84733392010-10-01 07:13:18 +00007767
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007768 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007769 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007770
Chris Lattnerecd79c62009-06-14 00:45:47 +00007771 return Type;
7772}
7773
7774/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007775QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007776 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007777 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007778 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007779
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007780 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007781
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007782 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007783 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007784 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7785 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007786 if (Error != GE_None)
7787 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007788
7789 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7790
Chris Lattnerecd79c62009-06-14 00:45:47 +00007791 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007792 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007793 if (Error != GE_None)
7794 return QualType();
7795
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007796 // If this argument is required to be an IntegerConstantExpression and the
7797 // caller cares, fill in the bitmask we return.
7798 if (RequiresICE && IntegerConstantArgs)
7799 *IntegerConstantArgs |= 1 << ArgTypes.size();
7800
Chris Lattnerecd79c62009-06-14 00:45:47 +00007801 // Do array -> pointer decay. The builtin should use the decayed type.
7802 if (Ty->isArrayType())
7803 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007804
Chris Lattnerecd79c62009-06-14 00:45:47 +00007805 ArgTypes.push_back(Ty);
7806 }
7807
7808 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7809 "'.' should only occur at end of builtin type list!");
7810
Reid Kleckner78af0702013-08-27 23:08:25 +00007811 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007812 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7813
7814 bool Variadic = (TypeStr[0] == '.');
7815
7816 // We really shouldn't be making a no-proto type here, especially in C++.
7817 if (ArgTypes.empty() && Variadic)
7818 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007819
John McCalldb40c7f2010-12-14 08:05:40 +00007820 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007821 EPI.ExtInfo = EI;
7822 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007823
Jordan Rose5c382722013-03-08 21:51:21 +00007824 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007825}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007826
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007827static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7828 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007829 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007830 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007831
Rafael Espindola3ae00052013-05-13 00:12:11 +00007832 GVALinkage External = GVA_StrongExternal;
7833 switch (FD->getTemplateSpecializationKind()) {
7834 case TSK_Undeclared:
7835 case TSK_ExplicitSpecialization:
7836 External = GVA_StrongExternal;
7837 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007838
Rafael Espindola3ae00052013-05-13 00:12:11 +00007839 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007840 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007841
David Majnemerc3d07332014-05-15 06:25:57 +00007842 // C++11 [temp.explicit]p10:
7843 // [ Note: The intent is that an inline function that is the subject of
7844 // an explicit instantiation declaration will still be implicitly
7845 // instantiated when used so that the body can be considered for
7846 // inlining, but that no out-of-line copy of the inline function would be
7847 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007848 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007849 return GVA_AvailableExternally;
7850
Rafael Espindola3ae00052013-05-13 00:12:11 +00007851 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007852 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007853 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007854 }
7855
7856 if (!FD->isInlined())
7857 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007858
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007859 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7860 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007861 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007862 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7863
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007864 // GNU or C99 inline semantics. Determine whether this symbol should be
7865 // externally visible.
7866 if (FD->isInlineDefinitionExternallyVisible())
7867 return External;
7868
7869 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007870 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007871 }
7872
David Majnemer54e3ba52014-04-02 23:17:29 +00007873 // Functions specified with extern and inline in -fms-compatibility mode
7874 // forcibly get emitted. While the body of the function cannot be later
7875 // replaced, the function definition cannot be discarded.
7876 if (FD->getMostRecentDecl()->isMSExternInline())
7877 return GVA_StrongODR;
7878
David Majnemer27d69db2014-04-28 22:17:59 +00007879 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007880}
7881
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007882static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7883 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7884 // dllexport/dllimport on inline functions.
7885 if (D->hasAttr<DLLImportAttr>()) {
7886 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7887 return GVA_AvailableExternally;
7888 } else if (D->hasAttr<DLLExportAttr>()) {
7889 if (L == GVA_DiscardableODR)
7890 return GVA_StrongODR;
7891 }
7892 return L;
7893}
7894
7895GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7896 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7897 FD);
7898}
7899
7900static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7901 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007902 if (!VD->isExternallyVisible())
7903 return GVA_Internal;
7904
David Majnemer27d69db2014-04-28 22:17:59 +00007905 if (VD->isStaticLocal()) {
7906 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7907 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7908 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7909 LexicalContext = LexicalContext->getLexicalParent();
7910
7911 // Let the static local variable inherit it's linkage from the nearest
7912 // enclosing function.
7913 if (LexicalContext)
7914 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007915 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007916
7917 // GVA_StrongODR function linkage is stronger than what we need,
7918 // downgrade to GVA_DiscardableODR.
7919 // This allows us to discard the variable if we never end up needing it.
7920 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7921 : StaticLocalLinkage;
7922 }
7923
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007924 // MSVC treats in-class initialized static data members as definitions.
7925 // By giving them non-strong linkage, out-of-line definitions won't
7926 // cause link errors.
7927 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7928 return GVA_DiscardableODR;
7929
Richard Smith8809a0c2013-09-27 20:14:12 +00007930 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007931 case TSK_Undeclared:
7932 case TSK_ExplicitSpecialization:
7933 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007934
Rafael Espindola3ae00052013-05-13 00:12:11 +00007935 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007936 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007937
David Majnemer27d69db2014-04-28 22:17:59 +00007938 case TSK_ExplicitInstantiationDeclaration:
7939 return GVA_AvailableExternally;
7940
Rafael Espindola3ae00052013-05-13 00:12:11 +00007941 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007942 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007943 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007944
7945 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007946}
7947
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007948GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7949 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7950 VD);
7951}
7952
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007953bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007954 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7955 if (!VD->isFileVarDecl())
7956 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00007957 // Global named register variables (GNU extension) are never emitted.
7958 if (VD->getStorageClass() == SC_Register)
7959 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007960 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7961 // We never need to emit an uninstantiated function template.
7962 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7963 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00007964 } else if (isa<OMPThreadPrivateDecl>(D))
7965 return true;
7966 else
Richard Smith5205a8c2013-04-01 20:22:16 +00007967 return false;
7968
7969 // If this is a member of a class template, we do not need to emit it.
7970 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007971 return false;
7972
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007973 // Weak references don't produce any output by themselves.
7974 if (D->hasAttr<WeakRefAttr>())
7975 return false;
7976
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007977 // Aliases and used decls are required.
7978 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7979 return true;
7980
7981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7982 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007983 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007984 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007985
7986 // Constructors and destructors are required.
7987 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7988 return true;
7989
John McCall6bd2a892013-01-25 22:31:03 +00007990 // The key function for a class is required. This rule only comes
7991 // into play when inline functions can be key functions, though.
7992 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7993 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7994 const CXXRecordDecl *RD = MD->getParent();
7995 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7996 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7997 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7998 return true;
7999 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008000 }
8001 }
8002
8003 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8004
8005 // static, static inline, always_inline, and extern inline functions can
8006 // always be deferred. Normal inline functions can be deferred in C99/C++.
8007 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008008 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8009 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008010 return false;
8011 return true;
8012 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008013
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008014 const VarDecl *VD = cast<VarDecl>(D);
8015 assert(VD->isFileVarDecl() && "Expected file scoped var");
8016
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008017 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8018 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008019 return false;
8020
Richard Smitha0e5e542012-11-12 21:38:00 +00008021 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008022 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008023 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8024 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008025 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008026
Richard Smitha0e5e542012-11-12 21:38:00 +00008027 // Variables that have destruction with side-effects are required.
8028 if (VD->getType().isDestructedType())
8029 return true;
8030
8031 // Variables that have initialization with side-effects are required.
8032 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8033 return true;
8034
8035 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008036}
Charles Davis53c59df2010-08-16 03:33:14 +00008037
Reid Kleckner78af0702013-08-27 23:08:25 +00008038CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8039 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008040 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008041 if (IsCXXMethod)
8042 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008043
Reid Kleckner78af0702013-08-27 23:08:25 +00008044 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00008045}
8046
Jay Foad39c79802011-01-12 09:06:06 +00008047bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008048 // Pass through to the C++ ABI object
8049 return ABI->isNearlyEmpty(RD);
8050}
8051
Reid Kleckner96f8f932014-02-05 17:27:08 +00008052VTableContextBase *ASTContext::getVTableContext() {
8053 if (!VTContext.get()) {
8054 if (Target->getCXXABI().isMicrosoft())
8055 VTContext.reset(new MicrosoftVTableContext(*this));
8056 else
8057 VTContext.reset(new ItaniumVTableContext(*this));
8058 }
8059 return VTContext.get();
8060}
8061
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008062MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008063 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008064 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008065 case TargetCXXABI::GenericItanium:
8066 case TargetCXXABI::GenericARM:
8067 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008068 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008069 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008070 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008071 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008072 }
David Blaikie83d382b2011-09-23 05:06:16 +00008073 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008074}
8075
Charles Davis53c59df2010-08-16 03:33:14 +00008076CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008077
8078size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008079 return ASTRecordLayouts.getMemorySize() +
8080 llvm::capacity_in_bytes(ObjCLayouts) +
8081 llvm::capacity_in_bytes(KeyFunctions) +
8082 llvm::capacity_in_bytes(ObjCImpls) +
8083 llvm::capacity_in_bytes(BlockVarCopyInits) +
8084 llvm::capacity_in_bytes(DeclAttrs) +
8085 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8086 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8087 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8088 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8089 llvm::capacity_in_bytes(OverriddenMethods) +
8090 llvm::capacity_in_bytes(Types) +
8091 llvm::capacity_in_bytes(VariableArrayTypes) +
8092 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008093}
Ted Kremenek540017e2011-10-06 05:00:56 +00008094
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008095/// getIntTypeForBitwidth -
8096/// sets integer QualTy according to specified details:
8097/// bitwidth, signed/unsigned.
8098/// Returns empty type if there is no appropriate target types.
8099QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8100 unsigned Signed) const {
8101 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8102 CanQualType QualTy = getFromTargetType(Ty);
8103 if (!QualTy && DestWidth == 128)
8104 return Signed ? Int128Ty : UnsignedInt128Ty;
8105 return QualTy;
8106}
8107
8108/// getRealTypeForBitwidth -
8109/// sets floating point QualTy according to specified bitwidth.
8110/// Returns empty type if there is no appropriate target types.
8111QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8112 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8113 switch (Ty) {
8114 case TargetInfo::Float:
8115 return FloatTy;
8116 case TargetInfo::Double:
8117 return DoubleTy;
8118 case TargetInfo::LongDouble:
8119 return LongDoubleTy;
8120 case TargetInfo::NoFloat:
8121 return QualType();
8122 }
8123
8124 llvm_unreachable("Unhandled TargetInfo::RealType value");
8125}
8126
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008127void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8128 if (Number > 1)
8129 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008130}
8131
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008132unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8133 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8134 MangleNumbers.find(ND);
8135 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008136}
8137
David Majnemer2206bf52014-03-05 08:57:59 +00008138void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8139 if (Number > 1)
8140 StaticLocalNumbers[VD] = Number;
8141}
8142
8143unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8144 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8145 StaticLocalNumbers.find(VD);
8146 return I != StaticLocalNumbers.end() ? I->second : 1;
8147}
8148
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008149MangleNumberingContext &
8150ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008151 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8152 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8153 if (!MCtx)
8154 MCtx = createMangleNumberingContext();
8155 return *MCtx;
8156}
8157
8158MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8159 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008160}
8161
Ted Kremenek540017e2011-10-06 05:00:56 +00008162void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8163 ParamIndices[D] = index;
8164}
8165
8166unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8167 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8168 assert(I != ParamIndices.end() &&
8169 "ParmIndices lacks entry set by ParmVarDecl");
8170 return I->second;
8171}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008172
Richard Smithe6c01442013-06-05 00:46:14 +00008173APValue *
8174ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8175 bool MayCreate) {
8176 assert(E && E->getStorageDuration() == SD_Static &&
8177 "don't need to cache the computed value for this temporary");
8178 if (MayCreate)
8179 return &MaterializedTemporaryValues[E];
8180
8181 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8182 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008183 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008184}
8185
Fariborz Jahanian615de762013-05-28 17:37:39 +00008186bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8187 const llvm::Triple &T = getTargetInfo().getTriple();
8188 if (!T.isOSDarwin())
8189 return false;
8190
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008191 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8192 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8193 return false;
8194
Fariborz Jahanian615de762013-05-28 17:37:39 +00008195 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8196 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8197 uint64_t Size = sizeChars.getQuantity();
8198 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8199 unsigned Align = alignChars.getQuantity();
8200 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8201 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8202}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008203
8204namespace {
8205
8206 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8207 /// parents as defined by the \c RecursiveASTVisitor.
8208 ///
8209 /// Note that the relationship described here is purely in terms of AST
8210 /// traversal - there are other relationships (for example declaration context)
8211 /// in the AST that are better modeled by special matchers.
8212 ///
8213 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8214 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8215
8216 public:
8217 /// \brief Builds and returns the translation unit's parent map.
8218 ///
8219 /// The caller takes ownership of the returned \c ParentMap.
8220 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8221 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8222 Visitor.TraverseDecl(&TU);
8223 return Visitor.Parents;
8224 }
8225
8226 private:
8227 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8228
8229 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8230 }
8231
8232 bool shouldVisitTemplateInstantiations() const {
8233 return true;
8234 }
8235 bool shouldVisitImplicitCode() const {
8236 return true;
8237 }
8238 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8239 // are not triggered during data recursion.
8240 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8241 return false;
8242 }
8243
8244 template <typename T>
8245 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008246 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008247 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008248 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008249 // FIXME: Currently we add the same parent multiple times, but only
8250 // when no memoization data is available for the type.
8251 // For example when we visit all subexpressions of template
8252 // instantiations; this is suboptimal, but benign: the only way to
8253 // visit those is with hasAncestor / hasParent, and those do not create
8254 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008255 // The plan is to enable DynTypedNode to be storable in a map or hash
8256 // map. The main problem there is to implement hash functions /
8257 // comparison operators for all types that DynTypedNode supports that
8258 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008259 auto &NodeOrVector = (*Parents)[Node];
8260 if (NodeOrVector.isNull()) {
8261 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008262 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008263 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8264 auto *Node =
8265 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8266 auto *Vector = new ASTContext::ParentVector(1, *Node);
8267 NodeOrVector = Vector;
8268 delete Node;
8269 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008270 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008271
8272 auto *Vector =
8273 NodeOrVector.template get<ASTContext::ParentVector *>();
8274 // Skip duplicates for types that have memoization data.
8275 // We must check that the type has memoization data before calling
8276 // std::find() because DynTypedNode::operator== can't compare all
8277 // types.
8278 bool Found = ParentStack.back().getMemoizationData() &&
8279 std::find(Vector->begin(), Vector->end(),
8280 ParentStack.back()) != Vector->end();
8281 if (!Found)
8282 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008283 }
8284 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008285 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8286 bool Result = (this ->* traverse) (Node);
8287 ParentStack.pop_back();
8288 return Result;
8289 }
8290
8291 bool TraverseDecl(Decl *DeclNode) {
8292 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8293 }
8294
8295 bool TraverseStmt(Stmt *StmtNode) {
8296 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8297 }
8298
8299 ASTContext::ParentMap *Parents;
8300 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8301
8302 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8303 };
8304
8305} // end namespace
8306
Benjamin Kramer07935292014-10-04 17:01:26 +00008307ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008308ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8309 assert(Node.getMemoizationData() &&
8310 "Invariant broken: only nodes that support memoization may be "
8311 "used in the parent map.");
8312 if (!AllParents) {
8313 // We always need to run over the whole translation unit, as
8314 // hasAncestor can escape any subtree.
8315 AllParents.reset(
8316 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8317 }
8318 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8319 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008320 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008321 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008322 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8323 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008324 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008325 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008326}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008327
8328bool
8329ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8330 const ObjCMethodDecl *MethodImpl) {
8331 // No point trying to match an unavailable/deprecated mothod.
8332 if (MethodDecl->hasAttr<UnavailableAttr>()
8333 || MethodDecl->hasAttr<DeprecatedAttr>())
8334 return false;
8335 if (MethodDecl->getObjCDeclQualifier() !=
8336 MethodImpl->getObjCDeclQualifier())
8337 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008338 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008339 return false;
8340
8341 if (MethodDecl->param_size() != MethodImpl->param_size())
8342 return false;
8343
8344 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8345 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8346 EF = MethodDecl->param_end();
8347 IM != EM && IF != EF; ++IM, ++IF) {
8348 const ParmVarDecl *DeclVar = (*IF);
8349 const ParmVarDecl *ImplVar = (*IM);
8350 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8351 return false;
8352 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8353 return false;
8354 }
8355 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8356
8357}
Richard Smith053f6c62014-05-16 23:01:30 +00008358
8359// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8360// doesn't include ASTContext.h
8361template
8362clang::LazyGenerationalUpdatePtr<
8363 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8364clang::LazyGenerationalUpdatePtr<
8365 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8366 const clang::ASTContext &Ctx, Decl *Value);