blob: 09638916cf00443c51763e49a49a274544075356 [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
702 4, // cuda_device
703 5, // cuda_constant
704 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000705 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000706 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 }
710}
711
David Tweed31d09b02013-09-13 12:04:22 +0000712static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
713 const LangOptions &LangOpts) {
714 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000715 case LangOptions::ASMM_Target:
716 return TI.useAddressSpaceMapMangling();
717 case LangOptions::ASMM_On:
718 return true;
719 case LangOptions::ASMM_Off:
720 return false;
721 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000722 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000723}
724
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000725ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000726 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000727 Builtin::Context &builtins)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 : FunctionProtoTypes(this_()),
729 TemplateSpecializationTypes(this_()),
730 DependentTemplateSpecializationTypes(this_()),
731 SubstTemplateTemplateParmPacks(this_()),
Craig Topper36250ad2014-05-12 05:36:57 +0000732 GlobalNestedNameSpecifier(nullptr),
733 Int128Decl(nullptr), UInt128Decl(nullptr), Float128StubDecl(nullptr),
734 BuiltinVaListDecl(nullptr),
735 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
736 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738 FILEDecl(nullptr),
739 jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
740 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
741 cudaConfigureCallDecl(nullptr),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000742 NullTypeSourceInfo(QualType()),
743 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000744 SourceMgr(SM), LangOpts(LOpts),
Craig Topper36250ad2014-05-12 05:36:57 +0000745 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000746 Idents(idents), Selectors(sels),
747 BuiltinInfo(builtins),
748 DeclarationNames(*this),
Craig Topper36250ad2014-05-12 05:36:57 +0000749 ExternalSource(nullptr), Listener(nullptr),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000750 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000751 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Craig Topper36250ad2014-05-12 05:36:57 +0000752 LastSDM(nullptr, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000753{
Daniel Dunbar221fa942008-08-11 04:54:23 +0000754 TUDecl = TranslationUnitDecl::Create(*this);
755}
756
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000757ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000758 ReleaseParentMapEntries();
759
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000760 // Release the DenseMaps associated with DeclContext objects.
761 // FIXME: Is this the ideal solution?
762 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000763
Manuel Klimeka7328992013-06-03 13:51:33 +0000764 // Call all of the deallocation functions on all of their targets.
765 for (DeallocationMap::const_iterator I = Deallocations.begin(),
766 E = Deallocations.end(); I != E; ++I)
767 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
768 (I->first)((I->second)[J]);
769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.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
Ted Kremenek076baeb2010-06-08 23:00:58 +0000779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 R->Destroy(*this);
784 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
788 A != AEnd; ++A)
789 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000790
Reid Kleckner588c9372014-02-19 23:44:52 +0000791 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000792}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000793
Manuel Klimek95403e62014-05-21 13:28:59 +0000794void ASTContext::ReleaseParentMapEntries() {
795 if (!AllParents) return;
796 for (const auto &Entry : *AllParents) {
797 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
798 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
799 } else {
800 assert(Entry.second.is<ParentVector *>());
801 delete Entry.second.get<ParentVector *>();
802 }
803 }
804}
805
Douglas Gregor1a809332010-05-23 18:26:36 +0000806void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000807 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000808}
809
Mike Stump11289f42009-09-09 15:08:12 +0000810void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000811ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
812 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000813}
814
Chris Lattner4eb445d2007-01-26 01:27:23 +0000815void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000816 llvm::errs() << "\n*** AST Context Stats:\n";
817 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000818
Douglas Gregora30d0462009-05-26 14:40:08 +0000819 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000820#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000821#define ABSTRACT_TYPE(Name, Parent)
822#include "clang/AST/TypeNodes.def"
823 0 // Extra
824 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000825
Chris Lattner4eb445d2007-01-26 01:27:23 +0000826 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
827 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000828 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000829 }
830
Douglas Gregora30d0462009-05-26 14:40:08 +0000831 unsigned Idx = 0;
832 unsigned TotalBytes = 0;
833#define TYPE(Name, Parent) \
834 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000835 llvm::errs() << " " << counts[Idx] << " " << #Name \
836 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000837 TotalBytes += counts[Idx] * sizeof(Name##Type); \
838 ++Idx;
839#define ABSTRACT_TYPE(Name, Parent)
840#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000841
Chandler Carruth3c147a72011-07-04 05:32:14 +0000842 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
843
Douglas Gregor7454c562010-07-02 20:37:36 +0000844 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
846 << NumImplicitDefaultConstructors
847 << " implicit default constructors created\n";
848 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
849 << NumImplicitCopyConstructors
850 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000851 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000852 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
853 << NumImplicitMoveConstructors
854 << " implicit move constructors created\n";
855 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
856 << NumImplicitCopyAssignmentOperators
857 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000858 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000859 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
860 << NumImplicitMoveAssignmentOperators
861 << " implicit move assignment operators created\n";
862 llvm::errs() << NumImplicitDestructorsDeclared << "/"
863 << NumImplicitDestructors
864 << " implicit destructors created\n";
865
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000866 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000867 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000868 ExternalSource->PrintStats();
869 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000870
Douglas Gregor5b11d492010-07-25 17:53:33 +0000871 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000872}
873
Alp Toker2dea15b2013-12-17 01:22:38 +0000874RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
875 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000876 SourceLocation Loc;
877 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000878 if (getLangOpts().CPlusPlus)
879 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
880 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000881 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000882 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
883 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000884 NewDecl->setImplicit();
885 return NewDecl;
886}
887
888TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
889 StringRef Name) const {
890 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
891 TypedefDecl *NewDecl = TypedefDecl::Create(
892 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
893 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
894 NewDecl->setImplicit();
895 return NewDecl;
896}
897
Douglas Gregor801c99d2011-08-12 06:49:56 +0000898TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000899 if (!Int128Decl)
900 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000901 return Int128Decl;
902}
903
904TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000905 if (!UInt128Decl)
906 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000907 return UInt128Decl;
908}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000909
Nico Webere1687c52013-06-20 21:44:55 +0000910TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000911 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000912 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000913 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000914
Nico Webere1687c52013-06-20 21:44:55 +0000915 return Float128StubDecl;
916}
917
John McCall48f2d582009-10-23 23:03:21 +0000918void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000919 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000920 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000921 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000922}
923
Douglas Gregore8bbc122011-09-02 00:18:52 +0000924void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
925 assert((!this->Target || this->Target == &Target) &&
926 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000927 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000928
Douglas Gregore8bbc122011-09-02 00:18:52 +0000929 this->Target = &Target;
930
931 ABI.reset(createCXXABI(Target));
932 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000933 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000934
Chris Lattner970e54e2006-11-12 00:37:36 +0000935 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000936 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner970e54e2006-11-12 00:37:36 +0000938 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000939 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000940 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000941 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000942 InitBuiltinType(CharTy, BuiltinType::Char_S);
943 else
944 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000945 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000946 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
947 InitBuiltinType(ShortTy, BuiltinType::Short);
948 InitBuiltinType(IntTy, BuiltinType::Int);
949 InitBuiltinType(LongTy, BuiltinType::Long);
950 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000951
Chris Lattner970e54e2006-11-12 00:37:36 +0000952 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000953 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
954 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
955 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
956 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
957 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000958
Chris Lattner970e54e2006-11-12 00:37:36 +0000959 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000960 InitBuiltinType(FloatTy, BuiltinType::Float);
961 InitBuiltinType(DoubleTy, BuiltinType::Double);
962 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000963
Chris Lattnerf122cef2009-04-30 02:43:43 +0000964 // GNU extension, 128-bit integers.
965 InitBuiltinType(Int128Ty, BuiltinType::Int128);
966 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
967
Hans Wennborg0d81e012013-05-10 10:08:40 +0000968 // C++ 3.9.1p5
969 if (TargetInfo::isTypeSigned(Target.getWCharType()))
970 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
971 else // -fshort-wchar makes wchar_t be unsigned.
972 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
973 if (LangOpts.CPlusPlus && LangOpts.WChar)
974 WideCharTy = WCharTy;
975 else {
976 // C99 (or C++ using -fno-wchar).
977 WideCharTy = getFromTargetType(Target.getWCharType());
978 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000979
James Molloy36365542012-05-04 10:55:22 +0000980 WIntTy = getFromTargetType(Target.getWIntType());
981
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000982 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
983 InitBuiltinType(Char16Ty, BuiltinType::Char16);
984 else // C99
985 Char16Ty = getFromTargetType(Target.getChar16Type());
986
987 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
988 InitBuiltinType(Char32Ty, BuiltinType::Char32);
989 else // C99
990 Char32Ty = getFromTargetType(Target.getChar32Type());
991
Douglas Gregor4619e432008-12-05 23:32:09 +0000992 // Placeholder type for type-dependent expressions whose type is
993 // completely unknown. No code should ever check a type against
994 // DependentTy and users should never see it; however, it is here to
995 // help diagnose failures to properly check for type-dependent
996 // expressions.
997 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998
John McCall36e7fe32010-10-12 00:20:44 +0000999 // Placeholder type for functions.
1000 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1001
John McCall0009fcc2011-04-26 20:42:42 +00001002 // Placeholder type for bound members.
1003 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1004
John McCall526ab472011-10-25 17:37:35 +00001005 // Placeholder type for pseudo-objects.
1006 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1007
John McCall31996342011-04-07 08:22:57 +00001008 // "any" type; useful for debugger-like clients.
1009 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1010
John McCall8a6b59a2011-10-17 18:09:15 +00001011 // Placeholder type for unbridged ARC casts.
1012 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1013
Eli Friedman34866c72012-08-31 00:14:07 +00001014 // Placeholder type for builtin functions.
1015 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1016
Chris Lattner970e54e2006-11-12 00:37:36 +00001017 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001018 FloatComplexTy = getComplexType(FloatTy);
1019 DoubleComplexTy = getComplexType(DoubleTy);
1020 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001021
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001022 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001023 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1024 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001025 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001026
1027 if (LangOpts.OpenCL) {
1028 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1029 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1030 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1031 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1032 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1033 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001034
Guy Benyei61054192013-02-07 10:55:47 +00001035 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001036 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001037 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001038
1039 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001040 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1041 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001042
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001043 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001044
1045 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001046
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001047 // void * type
1048 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001049
1050 // nullptr type (C++0x 2.14.7)
1051 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001052
1053 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1054 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001055
1056 // Builtin type used to help define __builtin_va_list.
1057 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001058}
1059
David Blaikie9c902b52011-09-25 23:23:43 +00001060DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001061 return SourceMgr.getDiagnostics();
1062}
1063
Douglas Gregor561eceb2010-08-30 16:49:28 +00001064AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1065 AttrVec *&Result = DeclAttrs[D];
1066 if (!Result) {
1067 void *Mem = Allocate(sizeof(AttrVec));
1068 Result = new (Mem) AttrVec;
1069 }
1070
1071 return *Result;
1072}
1073
1074/// \brief Erase the attributes corresponding to the given declaration.
1075void ASTContext::eraseDeclAttrs(const Decl *D) {
1076 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1077 if (Pos != DeclAttrs.end()) {
1078 Pos->second->~AttrVec();
1079 DeclAttrs.erase(Pos);
1080 }
1081}
1082
Larisse Voufo39a1e502013-08-06 01:03:05 +00001083// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001084MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001085ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001086 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001087 return getTemplateOrSpecializationInfo(Var)
1088 .dyn_cast<MemberSpecializationInfo *>();
1089}
1090
1091ASTContext::TemplateOrSpecializationInfo
1092ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1093 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1094 TemplateOrInstantiation.find(Var);
1095 if (Pos == TemplateOrInstantiation.end())
1096 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001097
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001098 return Pos->second;
1099}
1100
Mike Stump11289f42009-09-09 15:08:12 +00001101void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001102ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001103 TemplateSpecializationKind TSK,
1104 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001105 assert(Inst->isStaticDataMember() && "Not a static data member");
1106 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001107 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1108 Tmpl, TSK, PointOfInstantiation));
1109}
1110
1111void
1112ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1113 TemplateOrSpecializationInfo TSI) {
1114 assert(!TemplateOrInstantiation[Inst] &&
1115 "Already noted what the variable was instantiated from");
1116 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001117}
1118
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001119FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1120 const FunctionDecl *FD){
1121 assert(FD && "Specialization is 0");
1122 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001123 = ClassScopeSpecializationPattern.find(FD);
1124 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001125 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001126
1127 return Pos->second;
1128}
1129
1130void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1131 FunctionDecl *Pattern) {
1132 assert(FD && "Specialization is 0");
1133 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001134 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001135}
1136
John McCalle61f2ba2009-11-18 02:36:19 +00001137NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001138ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001139 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001140 = InstantiatedFromUsingDecl.find(UUD);
1141 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001142 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001143
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001144 return Pos->second;
1145}
1146
1147void
John McCallb96ec562009-12-04 22:46:56 +00001148ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1149 assert((isa<UsingDecl>(Pattern) ||
1150 isa<UnresolvedUsingValueDecl>(Pattern) ||
1151 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1152 "pattern decl is not a using decl");
1153 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1154 InstantiatedFromUsingDecl[Inst] = Pattern;
1155}
1156
1157UsingShadowDecl *
1158ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1159 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1160 = InstantiatedFromUsingShadowDecl.find(Inst);
1161 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001162 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001163
1164 return Pos->second;
1165}
1166
1167void
1168ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1169 UsingShadowDecl *Pattern) {
1170 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1171 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001172}
1173
Anders Carlsson5da84842009-09-01 04:26:58 +00001174FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1175 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1176 = InstantiatedFromUnnamedFieldDecl.find(Field);
1177 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001178 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001179
Anders Carlsson5da84842009-09-01 04:26:58 +00001180 return Pos->second;
1181}
1182
1183void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1184 FieldDecl *Tmpl) {
1185 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1186 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1187 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1188 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001189
Anders Carlsson5da84842009-09-01 04:26:58 +00001190 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1191}
1192
Douglas Gregor832940b2010-03-02 23:58:15 +00001193ASTContext::overridden_cxx_method_iterator
1194ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1195 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001196 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001197 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001198 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001199
1200 return Pos->second.begin();
1201}
1202
1203ASTContext::overridden_cxx_method_iterator
1204ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1205 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001206 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001207 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001208 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001209
1210 return Pos->second.end();
1211}
1212
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001213unsigned
1214ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1215 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001216 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001217 if (Pos == OverriddenMethods.end())
1218 return 0;
1219
1220 return Pos->second.size();
1221}
1222
Douglas Gregor832940b2010-03-02 23:58:15 +00001223void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1224 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001225 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001226 OverriddenMethods[Method].push_back(Overridden);
1227}
1228
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001229void ASTContext::getOverriddenMethods(
1230 const NamedDecl *D,
1231 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001232 assert(D);
1233
1234 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001235 Overridden.append(overridden_methods_begin(CXXMethod),
1236 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001237 return;
1238 }
1239
1240 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1241 if (!Method)
1242 return;
1243
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001244 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1245 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001246 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001247}
1248
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001249void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1250 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1251 assert(!Import->isFromASTFile() && "Non-local import declaration");
1252 if (!FirstLocalImport) {
1253 FirstLocalImport = Import;
1254 LastLocalImport = Import;
1255 return;
1256 }
1257
1258 LastLocalImport->NextLocalImport = Import;
1259 LastLocalImport = Import;
1260}
1261
Chris Lattner53cfe802007-07-18 17:52:12 +00001262//===----------------------------------------------------------------------===//
1263// Type Sizing and Analysis
1264//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001265
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001266/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1267/// scalar floating point type.
1268const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001269 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001270 assert(BT && "Not a floating point type!");
1271 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001272 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001273 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001274 case BuiltinType::Float: return Target->getFloatFormat();
1275 case BuiltinType::Double: return Target->getDoubleFormat();
1276 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001277 }
1278}
1279
Rafael Espindola71eccb32013-08-08 19:53:46 +00001280CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001281 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001282
John McCall94268702010-10-08 18:24:19 +00001283 bool UseAlignAttrOnly = false;
1284 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1285 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001286
John McCall94268702010-10-08 18:24:19 +00001287 // __attribute__((aligned)) can increase or decrease alignment
1288 // *except* on a struct or struct member, where it only increases
1289 // alignment unless 'packed' is also specified.
1290 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001291 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001292 // ignore that possibility; Sema should diagnose it.
1293 if (isa<FieldDecl>(D)) {
1294 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1295 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1296 } else {
1297 UseAlignAttrOnly = true;
1298 }
1299 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001300 else if (isa<FieldDecl>(D))
1301 UseAlignAttrOnly =
1302 D->hasAttr<PackedAttr>() ||
1303 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001304
John McCall4e819612011-01-20 07:57:12 +00001305 // If we're using the align attribute only, just ignore everything
1306 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001307 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001308 // do nothing
1309
John McCall94268702010-10-08 18:24:19 +00001310 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001311 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001312 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001313 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001314 T = RT->getPointeeType();
1315 else
1316 T = getPointerType(RT->getPointeeType());
1317 }
Richard Smithf6d70302014-06-10 23:34:28 +00001318 QualType BaseT = getBaseElementType(T);
1319 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001320 // Adjust alignments of declarations with array type by the
1321 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001322 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001323 unsigned MinWidth = Target->getLargeArrayMinWidth();
1324 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001325 if (isa<VariableArrayType>(arrayType))
1326 Align = std::max(Align, Target->getLargeArrayAlign());
1327 else if (isa<ConstantArrayType>(arrayType) &&
1328 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1329 Align = std::max(Align, Target->getLargeArrayAlign());
1330 }
John McCall33ddac02011-01-19 10:06:00 +00001331 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001332 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001333 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1334 if (VD->hasGlobalStorage())
1335 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1336 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001337 }
John McCall4e819612011-01-20 07:57:12 +00001338
1339 // Fields can be subject to extra alignment constraints, like if
1340 // the field is packed, the struct is packed, or the struct has a
1341 // a max-field-alignment constraint (#pragma pack). So calculate
1342 // the actual alignment of the field within the struct, and then
1343 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001344 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1345 const RecordDecl *Parent = Field->getParent();
1346 // We can only produce a sensible answer if the record is valid.
1347 if (!Parent->isInvalidDecl()) {
1348 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001349
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001350 // Start with the record's overall alignment.
1351 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001352
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001353 // Use the GCD of that and the offset within the record.
1354 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1355 if (Offset > 0) {
1356 // Alignment is always a power of 2, so the GCD will be a power of 2,
1357 // which means we get to do this crazy thing instead of Euclid's.
1358 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1359 if (LowBitOfOffset < FieldAlign)
1360 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1361 }
1362
1363 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001364 }
Charles Davis3fc51072010-02-23 04:52:00 +00001365 }
Chris Lattner68061312009-01-24 21:53:27 +00001366 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001367
Ken Dyckcc56c542011-01-15 18:38:59 +00001368 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001369}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001370
John McCallf1249922012-08-21 04:10:00 +00001371// getTypeInfoDataSizeInChars - Return the size of a type, in
1372// chars. If the type is a record, its data size is returned. This is
1373// the size of the memcpy that's performed when assigning this type
1374// using a trivial copy/move assignment operator.
1375std::pair<CharUnits, CharUnits>
1376ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1377 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1378
1379 // In C++, objects can sometimes be allocated into the tail padding
1380 // of a base-class subobject. We decide whether that's possible
1381 // during class layout, so here we can just trust the layout results.
1382 if (getLangOpts().CPlusPlus) {
1383 if (const RecordType *RT = T->getAs<RecordType>()) {
1384 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1385 sizeAndAlign.first = layout.getDataSize();
1386 }
1387 }
1388
1389 return sizeAndAlign;
1390}
1391
Richard Trieu04d2d942013-05-14 21:59:17 +00001392/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1393/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1394std::pair<CharUnits, CharUnits>
1395static getConstantArrayInfoInChars(const ASTContext &Context,
1396 const ConstantArrayType *CAT) {
1397 std::pair<CharUnits, CharUnits> EltInfo =
1398 Context.getTypeInfoInChars(CAT->getElementType());
1399 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001400 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1401 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001402 "Overflow in array type char size evaluation");
1403 uint64_t Width = EltInfo.first.getQuantity() * Size;
1404 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001405 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1406 Context.getTargetInfo().getPointerWidth(0) == 64)
1407 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001408 return std::make_pair(CharUnits::fromQuantity(Width),
1409 CharUnits::fromQuantity(Align));
1410}
1411
John McCall87fe5d52010-05-20 01:18:31 +00001412std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001413ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001414 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1415 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001416 TypeInfo Info = getTypeInfo(T);
1417 return std::make_pair(toCharUnitsFromBits(Info.Width),
1418 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001419}
1420
1421std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001422ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001423 return getTypeInfoInChars(T.getTypePtr());
1424}
1425
David Majnemer34b57492014-07-30 01:30:47 +00001426bool ASTContext::isAlignmentRequired(const Type *T) const {
1427 return getTypeInfo(T).AlignIsRequired;
1428}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001429
David Majnemer34b57492014-07-30 01:30:47 +00001430bool ASTContext::isAlignmentRequired(QualType T) const {
1431 return isAlignmentRequired(T.getTypePtr());
1432}
1433
1434TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001435 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1436 if (I != MemoizedTypeInfo.end())
1437 return I->second;
1438
1439 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1440 TypeInfo TI = getTypeInfoImpl(T);
1441 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001442 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001443}
1444
1445/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1446/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001447///
1448/// FIXME: Pointers into different addr spaces could have different sizes and
1449/// alignment requirements: getPointerInfo should take an AddrSpace, this
1450/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001451TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1452 uint64_t Width = 0;
1453 unsigned Align = 8;
1454 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001455 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001456#define TYPE(Class, Base)
1457#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001458#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001459#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001460#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1461 case Type::Class: \
1462 assert(!T->isDependentType() && "should not see dependent types here"); \
1463 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001464#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001465 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001466
Chris Lattner355332d2007-07-13 22:27:08 +00001467 case Type::FunctionNoProto:
1468 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001469 // GCC extension: alignof(function) = 32 bits
1470 Width = 0;
1471 Align = 32;
1472 break;
1473
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001474 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001475 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001476 Width = 0;
1477 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1478 break;
1479
Steve Naroff5c131802007-08-30 01:06:46 +00001480 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001481 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001482
David Majnemer34b57492014-07-30 01:30:47 +00001483 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001484 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001485 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001486 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001487 Width = EltInfo.Width * Size;
1488 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001489 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1490 getTargetInfo().getPointerWidth(0) == 64)
1491 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001492 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001493 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001494 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001495 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001496 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001497 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1498 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001499 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001500 // If the alignment is not a power of 2, round up to the next power of 2.
1501 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001502 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001503 Align = llvm::NextPowerOf2(Align);
1504 Width = llvm::RoundUpToAlignment(Width, Align);
1505 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001506 // Adjust the alignment based on the target max.
1507 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1508 if (TargetVectorAlign && TargetVectorAlign < Align)
1509 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001510 break;
1511 }
Chris Lattner647fb222007-07-18 18:26:58 +00001512
Chris Lattner7570e9c2008-03-08 08:52:55 +00001513 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001514 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001515 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001516 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001517 // GCC extension: alignof(void) = 8 bits.
1518 Width = 0;
1519 Align = 8;
1520 break;
1521
Chris Lattner6a4f7452007-12-19 19:23:28 +00001522 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001523 Width = Target->getBoolWidth();
1524 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001525 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001526 case BuiltinType::Char_S:
1527 case BuiltinType::Char_U:
1528 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 Width = Target->getCharWidth();
1531 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001533 case BuiltinType::WChar_S:
1534 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001535 Width = Target->getWCharWidth();
1536 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001537 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001538 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001539 Width = Target->getChar16Width();
1540 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001541 break;
1542 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001543 Width = Target->getChar32Width();
1544 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001545 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001546 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001547 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001548 Width = Target->getShortWidth();
1549 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001550 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001551 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001552 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001553 Width = Target->getIntWidth();
1554 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001555 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001556 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001557 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001558 Width = Target->getLongWidth();
1559 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001560 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001561 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001562 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001563 Width = Target->getLongLongWidth();
1564 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001565 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001566 case BuiltinType::Int128:
1567 case BuiltinType::UInt128:
1568 Width = 128;
1569 Align = 128; // int128_t is 128-bit aligned on all targets.
1570 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001571 case BuiltinType::Half:
1572 Width = Target->getHalfWidth();
1573 Align = Target->getHalfAlign();
1574 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001575 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001576 Width = Target->getFloatWidth();
1577 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001578 break;
1579 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001580 Width = Target->getDoubleWidth();
1581 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001582 break;
1583 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001584 Width = Target->getLongDoubleWidth();
1585 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001586 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001587 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001588 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1589 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001590 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001591 case BuiltinType::ObjCId:
1592 case BuiltinType::ObjCClass:
1593 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001594 Width = Target->getPointerWidth(0);
1595 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001596 break;
Guy Benyei61054192013-02-07 10:55:47 +00001597 case BuiltinType::OCLSampler:
1598 // Samplers are modeled as integers.
1599 Width = Target->getIntWidth();
1600 Align = Target->getIntAlign();
1601 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001602 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001603 case BuiltinType::OCLImage1d:
1604 case BuiltinType::OCLImage1dArray:
1605 case BuiltinType::OCLImage1dBuffer:
1606 case BuiltinType::OCLImage2d:
1607 case BuiltinType::OCLImage2dArray:
1608 case BuiltinType::OCLImage3d:
1609 // Currently these types are pointers to opaque types.
1610 Width = Target->getPointerWidth(0);
1611 Align = Target->getPointerAlign(0);
1612 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001613 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001614 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001615 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001616 Width = Target->getPointerWidth(0);
1617 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001618 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001619 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001620 unsigned AS = getTargetAddressSpace(
1621 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001622 Width = Target->getPointerWidth(AS);
1623 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001624 break;
1625 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001626 case Type::LValueReference:
1627 case Type::RValueReference: {
1628 // alignof and sizeof should never enter this code path here, so we go
1629 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001630 unsigned AS = getTargetAddressSpace(
1631 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001632 Width = Target->getPointerWidth(AS);
1633 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001634 break;
1635 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001636 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001637 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001638 Width = Target->getPointerWidth(AS);
1639 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001640 break;
1641 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001642 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001643 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001644 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001645 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001646 }
Chris Lattner647fb222007-07-18 18:26:58 +00001647 case Type::Complex: {
1648 // Complex types have the same alignment as their elements, but twice the
1649 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001650 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1651 Width = EltInfo.Width * 2;
1652 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001653 break;
1654 }
John McCall8b07ec22010-05-15 11:32:37 +00001655 case Type::ObjCObject:
1656 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001657 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001658 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001659 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001660 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001661 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001662 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001663 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001664 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001665 break;
1666 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001667 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001668 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001669 const TagType *TT = cast<TagType>(T);
1670
1671 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001672 Width = 8;
1673 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001674 break;
1675 }
Mike Stump11289f42009-09-09 15:08:12 +00001676
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001677 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001678 return getTypeInfo(ET->getDecl()->getIntegerType());
1679
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001680 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001681 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001682 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001683 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001684 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001685 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001686
Chris Lattner63d2b362009-10-22 05:17:15 +00001687 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001688 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1689 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001690
Richard Smith30482bc2011-02-20 03:19:35 +00001691 case Type::Auto: {
1692 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001693 assert(!A->getDeducedType().isNull() &&
1694 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001695 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001696 }
1697
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001698 case Type::Paren:
1699 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1700
Douglas Gregoref462e62009-04-30 17:32:17 +00001701 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001702 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001703 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001704 // If the typedef has an aligned attribute on it, it overrides any computed
1705 // alignment we have. This violates the GCC documentation (which says that
1706 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001707 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001708 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001709 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001710 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001711 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001712 AlignIsRequired = Info.AlignIsRequired;
1713 }
David Majnemer34b57492014-07-30 01:30:47 +00001714 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001715 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001716 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001717
Abramo Bagnara6150c882010-05-11 21:36:43 +00001718 case Type::Elaborated:
1719 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001720
John McCall81904512011-01-06 01:58:22 +00001721 case Type::Attributed:
1722 return getTypeInfo(
1723 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1724
Eli Friedman0dfb8892011-10-06 23:00:33 +00001725 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001726 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001727 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1728 Width = Info.Width;
1729 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001730
1731 // If the size of the type doesn't exceed the platform's max
1732 // atomic promotion width, make the size and alignment more
1733 // favorable to atomic operations:
1734 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1735 // Round the size up to a power of 2.
1736 if (!llvm::isPowerOf2_64(Width))
1737 Width = llvm::NextPowerOf2(Width);
1738
1739 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001740 Align = static_cast<unsigned>(Width);
1741 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001742 }
1743
Douglas Gregoref462e62009-04-30 17:32:17 +00001744 }
Mike Stump11289f42009-09-09 15:08:12 +00001745
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001746 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001747 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001748}
1749
Ken Dyckcc56c542011-01-15 18:38:59 +00001750/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1751CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1752 return CharUnits::fromQuantity(BitSize / getCharWidth());
1753}
1754
Ken Dyckb0fcc592011-02-11 01:54:29 +00001755/// toBits - Convert a size in characters to a size in characters.
1756int64_t ASTContext::toBits(CharUnits CharSize) const {
1757 return CharSize.getQuantity() * getCharWidth();
1758}
1759
Ken Dyck8c89d592009-12-22 14:23:30 +00001760/// getTypeSizeInChars - Return the size of the specified type, in characters.
1761/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001762CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001763 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001764}
Jay Foad39c79802011-01-12 09:06:06 +00001765CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001766 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001767}
1768
Ken Dycka6046ab2010-01-26 17:25:18 +00001769/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001770/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001771CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001772 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001773}
Jay Foad39c79802011-01-12 09:06:06 +00001774CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001775 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001776}
1777
Chris Lattnera3402cd2009-01-27 18:08:34 +00001778/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1779/// type for the current target in bits. This can be different than the ABI
1780/// alignment in cases where it is beneficial for performance to overalign
1781/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001782unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001783 TypeInfo TI = getTypeInfo(T);
1784 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001785
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001786 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1787 return ABIAlign; // Never overalign on XCore.
1788
Eli Friedman7ab09572009-05-25 21:27:19 +00001789 // Double and long long should be naturally aligned if possible.
Richard Smithd7e1fe42014-06-10 23:43:44 +00001790 T = T->getBaseElementTypeUnsafe();
David Majnemer1d4db8f2014-02-24 23:43:27 +00001791 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001792 T = CT->getElementType().getTypePtr();
1793 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001794 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1795 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001796 // Don't increase the alignment if an alignment attribute was specified on a
1797 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001798 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001799 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001800
Chris Lattnera3402cd2009-01-27 18:08:34 +00001801 return ABIAlign;
1802}
1803
Ulrich Weigandfa806422013-05-06 16:23:57 +00001804/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1805/// to a global variable of the specified type.
1806unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1807 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1808}
1809
1810/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1811/// should be given to a global variable of the specified type.
1812CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1813 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1814}
1815
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001816/// DeepCollectObjCIvars -
1817/// This routine first collects all declared, but not synthesized, ivars in
1818/// super class and then collects all ivars, including those synthesized for
1819/// current class. This routine is used for implementation of current class
1820/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001821///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001822void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1823 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001824 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001825 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1826 DeepCollectObjCIvars(SuperClass, false, Ivars);
1827 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001828 for (const auto *I : OI->ivars())
1829 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001830 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001831 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001832 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001833 Iv= Iv->getNextIvar())
1834 Ivars.push_back(Iv);
1835 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001836}
1837
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001838/// CollectInheritedProtocols - Collect all protocols in current class and
1839/// those inherited by it.
1840void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001841 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001842 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001843 // We can use protocol_iterator here instead of
1844 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001845 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001846 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001847 for (auto *P : Proto->protocols()) {
1848 Protocols.insert(P->getCanonicalDecl());
1849 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001850 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001851 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001852
1853 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001854 for (const auto *Cat : OI->visible_categories())
1855 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001856
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001857 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1858 while (SD) {
1859 CollectInheritedProtocols(SD, Protocols);
1860 SD = SD->getSuperClass();
1861 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001862 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001863 for (auto *Proto : OC->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 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001868 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001869 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001870 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001871 for (const auto *P : Proto->protocols())
1872 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001873 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001874 }
1875}
1876
Jay Foad39c79802011-01-12 09:06:06 +00001877unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001878 unsigned count = 0;
1879 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001880 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001881 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001882
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001883 // Count ivar defined in this class's implementation. This
1884 // includes synthesized ivars.
1885 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001886 count += ImplDecl->ivar_size();
1887
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001888 return count;
1889}
1890
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001891bool ASTContext::isSentinelNullExpr(const Expr *E) {
1892 if (!E)
1893 return false;
1894
1895 // nullptr_t is always treated as null.
1896 if (E->getType()->isNullPtrType()) return true;
1897
1898 if (E->getType()->isAnyPointerType() &&
1899 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1900 Expr::NPC_ValueDependentIsNull))
1901 return true;
1902
1903 // Unfortunately, __null has type 'int'.
1904 if (isa<GNUNullExpr>(E)) return true;
1905
1906 return false;
1907}
1908
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001909/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1910ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1911 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1912 I = ObjCImpls.find(D);
1913 if (I != ObjCImpls.end())
1914 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001915 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001916}
1917/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1918ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1919 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1920 I = ObjCImpls.find(D);
1921 if (I != ObjCImpls.end())
1922 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001923 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001924}
1925
1926/// \brief Set the implementation of ObjCInterfaceDecl.
1927void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1928 ObjCImplementationDecl *ImplD) {
1929 assert(IFaceD && ImplD && "Passed null params");
1930 ObjCImpls[IFaceD] = ImplD;
1931}
1932/// \brief Set the implementation of ObjCCategoryDecl.
1933void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1934 ObjCCategoryImplDecl *ImplD) {
1935 assert(CatD && ImplD && "Passed null params");
1936 ObjCImpls[CatD] = ImplD;
1937}
1938
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001939const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1940 const NamedDecl *ND) const {
1941 if (const ObjCInterfaceDecl *ID =
1942 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001943 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001944 if (const ObjCCategoryDecl *CD =
1945 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001946 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001947 if (const ObjCImplDecl *IMD =
1948 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001949 return IMD->getClassInterface();
1950
Craig Topper36250ad2014-05-12 05:36:57 +00001951 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001952}
1953
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001954/// \brief Get the copy initialization expression of VarDecl,or NULL if
1955/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001956Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001957 assert(VD && "Passed null params");
1958 assert(VD->hasAttr<BlocksAttr>() &&
1959 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001960 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001961 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001962 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001963}
1964
1965/// \brief Set the copy inialization expression of a block var decl.
1966void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1967 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001968 assert(VD->hasAttr<BlocksAttr>() &&
1969 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001970 BlockVarCopyInits[VD] = Init;
1971}
1972
John McCallbcd03502009-12-07 02:54:59 +00001973TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001974 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001975 if (!DataSize)
1976 DataSize = TypeLoc::getFullDataSizeForType(T);
1977 else
1978 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001979 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001980
John McCallbcd03502009-12-07 02:54:59 +00001981 TypeSourceInfo *TInfo =
1982 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1983 new (TInfo) TypeSourceInfo(T);
1984 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001985}
1986
John McCallbcd03502009-12-07 02:54:59 +00001987TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001988 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001989 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001990 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001991 return DI;
1992}
1993
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001994const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001995ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00001996 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001997}
1998
1999const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002000ASTContext::getASTObjCImplementationLayout(
2001 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002002 return getObjCLayout(D->getClassInterface(), D);
2003}
2004
Chris Lattner983a8bb2007-07-13 22:13:22 +00002005//===----------------------------------------------------------------------===//
2006// Type creation/memoization methods
2007//===----------------------------------------------------------------------===//
2008
Jay Foad39c79802011-01-12 09:06:06 +00002009QualType
John McCall33ddac02011-01-19 10:06:00 +00002010ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2011 unsigned fastQuals = quals.getFastQualifiers();
2012 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002013
2014 // Check if we've already instantiated this type.
2015 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002016 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002017 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002018 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2019 assert(eq->getQualifiers() == quals);
2020 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002021 }
2022
John McCall33ddac02011-01-19 10:06:00 +00002023 // If the base type is not canonical, make the appropriate canonical type.
2024 QualType canon;
2025 if (!baseType->isCanonicalUnqualified()) {
2026 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002027 canonSplit.Quals.addConsistentQualifiers(quals);
2028 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002029
2030 // Re-find the insert position.
2031 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2032 }
2033
2034 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2035 ExtQualNodes.InsertNode(eq, insertPos);
2036 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002037}
2038
Jay Foad39c79802011-01-12 09:06:06 +00002039QualType
2040ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002041 QualType CanT = getCanonicalType(T);
2042 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002043 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002044
John McCall8ccfcb52009-09-24 19:53:00 +00002045 // If we are composing extended qualifiers together, merge together
2046 // into one ExtQuals node.
2047 QualifierCollector Quals;
2048 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002049
John McCall8ccfcb52009-09-24 19:53:00 +00002050 // If this type already has an address space specified, it cannot get
2051 // another one.
2052 assert(!Quals.hasAddressSpace() &&
2053 "Type cannot be in multiple addr spaces!");
2054 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002055
John McCall8ccfcb52009-09-24 19:53:00 +00002056 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002057}
2058
Chris Lattnerd60183d2009-02-18 22:53:11 +00002059QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002060 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002061 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002062 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002063 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002064
John McCall53fa7142010-12-24 02:08:15 +00002065 if (const PointerType *ptr = T->getAs<PointerType>()) {
2066 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002067 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002068 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2069 return getPointerType(ResultType);
2070 }
2071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
John McCall8ccfcb52009-09-24 19:53:00 +00002073 // If we are composing extended qualifiers together, merge together
2074 // into one ExtQuals node.
2075 QualifierCollector Quals;
2076 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002077
John McCall8ccfcb52009-09-24 19:53:00 +00002078 // If this type already has an ObjCGC specified, it cannot get
2079 // another one.
2080 assert(!Quals.hasObjCGCAttr() &&
2081 "Type cannot have multiple ObjCGCs!");
2082 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002083
John McCall8ccfcb52009-09-24 19:53:00 +00002084 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002085}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002086
John McCall4f5019e2010-12-19 02:44:49 +00002087const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2088 FunctionType::ExtInfo Info) {
2089 if (T->getExtInfo() == Info)
2090 return T;
2091
2092 QualType Result;
2093 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002094 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002095 } else {
2096 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2097 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2098 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002099 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002100 }
2101
2102 return cast<FunctionType>(Result.getTypePtr());
2103}
2104
Richard Smith2a7d4812013-05-04 07:00:32 +00002105void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2106 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002107 FD = FD->getMostRecentDecl();
2108 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002109 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2110 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002111 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002112 if (FunctionDecl *Next = FD->getPreviousDecl())
2113 FD = Next;
2114 else
2115 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002116 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002117 if (ASTMutationListener *L = getASTMutationListener())
2118 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002119}
2120
Chris Lattnerc6395932007-06-22 20:56:16 +00002121/// getComplexType - Return the uniqued reference to the type for a complex
2122/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002123QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002124 // Unique pointers, to guarantee there is only one pointer of a particular
2125 // structure.
2126 llvm::FoldingSetNodeID ID;
2127 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002128
Craig Topper36250ad2014-05-12 05:36:57 +00002129 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002130 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2131 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002132
Chris Lattnerc6395932007-06-22 20:56:16 +00002133 // If the pointee type isn't canonical, this won't be a canonical type either,
2134 // so fill in the canonical type field.
2135 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002136 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002137 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002138
Chris Lattnerc6395932007-06-22 20:56:16 +00002139 // Get the new insert position for the node we care about.
2140 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002141 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002142 }
John McCall90d1c2d2009-09-24 23:30:46 +00002143 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002144 Types.push_back(New);
2145 ComplexTypes.InsertNode(New, InsertPos);
2146 return QualType(New, 0);
2147}
2148
Chris Lattner970e54e2006-11-12 00:37:36 +00002149/// getPointerType - Return the uniqued reference to the type for a pointer to
2150/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002151QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002152 // Unique pointers, to guarantee there is only one pointer of a particular
2153 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002154 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002155 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002156
Craig Topper36250ad2014-05-12 05:36:57 +00002157 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002158 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002159 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002160
Chris Lattner7ccecb92006-11-12 08:50:50 +00002161 // If the pointee type isn't canonical, this won't be a canonical type either,
2162 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002163 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002164 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002165 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002166
Bob Wilsonc8541f22013-03-15 17:12:43 +00002167 // Get the new insert position for the node we care about.
2168 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002169 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002170 }
John McCall90d1c2d2009-09-24 23:30:46 +00002171 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002172 Types.push_back(New);
2173 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002174 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002175}
2176
Reid Kleckner0503a872013-12-05 01:23:43 +00002177QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2178 llvm::FoldingSetNodeID ID;
2179 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002180 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002181 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2182 if (AT)
2183 return QualType(AT, 0);
2184
2185 QualType Canonical = getCanonicalType(New);
2186
2187 // Get the new insert position for the node we care about.
2188 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002189 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002190
2191 AT = new (*this, TypeAlignment)
2192 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2193 Types.push_back(AT);
2194 AdjustedTypes.InsertNode(AT, InsertPos);
2195 return QualType(AT, 0);
2196}
2197
Reid Kleckner8a365022013-06-24 17:51:48 +00002198QualType ASTContext::getDecayedType(QualType T) const {
2199 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2200
Reid Kleckner8a365022013-06-24 17:51:48 +00002201 QualType Decayed;
2202
2203 // C99 6.7.5.3p7:
2204 // A declaration of a parameter as "array of type" shall be
2205 // adjusted to "qualified pointer to type", where the type
2206 // qualifiers (if any) are those specified within the [ and ] of
2207 // the array type derivation.
2208 if (T->isArrayType())
2209 Decayed = getArrayDecayedType(T);
2210
2211 // C99 6.7.5.3p8:
2212 // A declaration of a parameter as "function returning type"
2213 // shall be adjusted to "pointer to function returning type", as
2214 // in 6.3.2.1.
2215 if (T->isFunctionType())
2216 Decayed = getPointerType(T);
2217
Reid Kleckner0503a872013-12-05 01:23:43 +00002218 llvm::FoldingSetNodeID ID;
2219 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002220 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002221 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2222 if (AT)
2223 return QualType(AT, 0);
2224
Reid Kleckner8a365022013-06-24 17:51:48 +00002225 QualType Canonical = getCanonicalType(Decayed);
2226
2227 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002228 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002229 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002230
Reid Kleckner0503a872013-12-05 01:23:43 +00002231 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2232 Types.push_back(AT);
2233 AdjustedTypes.InsertNode(AT, InsertPos);
2234 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002235}
2236
Mike Stump11289f42009-09-09 15:08:12 +00002237/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002238/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002239QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002240 assert(T->isFunctionType() && "block of function types only");
2241 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002242 // structure.
2243 llvm::FoldingSetNodeID ID;
2244 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002245
Craig Topper36250ad2014-05-12 05:36:57 +00002246 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002247 if (BlockPointerType *PT =
2248 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2249 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002250
2251 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002252 // type either so fill in the canonical type field.
2253 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002254 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002255 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002256
Steve Naroffec33ed92008-08-27 16:04:49 +00002257 // Get the new insert position for the node we care about.
2258 BlockPointerType *NewIP =
2259 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002260 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002261 }
John McCall90d1c2d2009-09-24 23:30:46 +00002262 BlockPointerType *New
2263 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002264 Types.push_back(New);
2265 BlockPointerTypes.InsertNode(New, InsertPos);
2266 return QualType(New, 0);
2267}
2268
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002269/// getLValueReferenceType - Return the uniqued reference to the type for an
2270/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002271QualType
2272ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002273 assert(getCanonicalType(T) != OverloadTy &&
2274 "Unresolved overloaded function type");
2275
Bill Wendling3708c182007-05-27 10:15:43 +00002276 // Unique pointers, to guarantee there is only one pointer of a particular
2277 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002278 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002279 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002280
Craig Topper36250ad2014-05-12 05:36:57 +00002281 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002282 if (LValueReferenceType *RT =
2283 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002284 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002285
John McCallfc93cf92009-10-22 22:37:11 +00002286 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2287
Bill Wendling3708c182007-05-27 10:15:43 +00002288 // If the referencee type isn't canonical, this won't be a canonical type
2289 // either, so fill in the canonical type field.
2290 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002291 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2292 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2293 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002294
Bill Wendling3708c182007-05-27 10:15:43 +00002295 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002296 LValueReferenceType *NewIP =
2297 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002298 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002299 }
2300
John McCall90d1c2d2009-09-24 23:30:46 +00002301 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002302 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2303 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002304 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002305 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002306
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002307 return QualType(New, 0);
2308}
2309
2310/// getRValueReferenceType - Return the uniqued reference to the type for an
2311/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002312QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002313 // Unique pointers, to guarantee there is only one pointer of a particular
2314 // structure.
2315 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002316 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002317
Craig Topper36250ad2014-05-12 05:36:57 +00002318 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002319 if (RValueReferenceType *RT =
2320 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2321 return QualType(RT, 0);
2322
John McCallfc93cf92009-10-22 22:37:11 +00002323 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2324
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002325 // If the referencee type isn't canonical, this won't be a canonical type
2326 // either, so fill in the canonical type field.
2327 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002328 if (InnerRef || !T.isCanonical()) {
2329 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2330 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002331
2332 // Get the new insert position for the node we care about.
2333 RValueReferenceType *NewIP =
2334 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002335 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002336 }
2337
John McCall90d1c2d2009-09-24 23:30:46 +00002338 RValueReferenceType *New
2339 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002340 Types.push_back(New);
2341 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002342 return QualType(New, 0);
2343}
2344
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002345/// getMemberPointerType - Return the uniqued reference to the type for a
2346/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002347QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002348 // Unique pointers, to guarantee there is only one pointer of a particular
2349 // structure.
2350 llvm::FoldingSetNodeID ID;
2351 MemberPointerType::Profile(ID, T, Cls);
2352
Craig Topper36250ad2014-05-12 05:36:57 +00002353 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002354 if (MemberPointerType *PT =
2355 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2356 return QualType(PT, 0);
2357
2358 // If the pointee or class type isn't canonical, this won't be a canonical
2359 // type either, so fill in the canonical type field.
2360 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002361 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002362 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2363
2364 // Get the new insert position for the node we care about.
2365 MemberPointerType *NewIP =
2366 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002367 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002368 }
John McCall90d1c2d2009-09-24 23:30:46 +00002369 MemberPointerType *New
2370 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002371 Types.push_back(New);
2372 MemberPointerTypes.InsertNode(New, InsertPos);
2373 return QualType(New, 0);
2374}
2375
Mike Stump11289f42009-09-09 15:08:12 +00002376/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002377/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002378QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002379 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002380 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002381 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002382 assert((EltTy->isDependentType() ||
2383 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002384 "Constant array of VLAs is illegal!");
2385
Chris Lattnere2df3f92009-05-13 04:12:56 +00002386 // Convert the array size into a canonical width matching the pointer size for
2387 // the target.
2388 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002389 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002390 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002391
Chris Lattner23b7eb62007-06-15 23:05:46 +00002392 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002393 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002394
Craig Topper36250ad2014-05-12 05:36:57 +00002395 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002396 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002397 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002398 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002399
John McCall33ddac02011-01-19 10:06:00 +00002400 // If the element type isn't canonical or has qualifiers, this won't
2401 // be a canonical type either, so fill in the canonical type field.
2402 QualType Canon;
2403 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2404 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002405 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002406 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002407 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002408
Chris Lattner36f8e652007-01-27 08:31:04 +00002409 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002410 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002411 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002412 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002413 }
Mike Stump11289f42009-09-09 15:08:12 +00002414
John McCall90d1c2d2009-09-24 23:30:46 +00002415 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002416 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002417 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002418 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002419 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002420}
2421
John McCall06549462011-01-18 08:40:38 +00002422/// getVariableArrayDecayedType - Turns the given type, which may be
2423/// variably-modified, into the corresponding type with all the known
2424/// sizes replaced with [*].
2425QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2426 // Vastly most common case.
2427 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002428
John McCall06549462011-01-18 08:40:38 +00002429 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002430
John McCall06549462011-01-18 08:40:38 +00002431 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002432 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002433 switch (ty->getTypeClass()) {
2434#define TYPE(Class, Base)
2435#define ABSTRACT_TYPE(Class, Base)
2436#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2437#include "clang/AST/TypeNodes.def"
2438 llvm_unreachable("didn't desugar past all non-canonical types?");
2439
2440 // These types should never be variably-modified.
2441 case Type::Builtin:
2442 case Type::Complex:
2443 case Type::Vector:
2444 case Type::ExtVector:
2445 case Type::DependentSizedExtVector:
2446 case Type::ObjCObject:
2447 case Type::ObjCInterface:
2448 case Type::ObjCObjectPointer:
2449 case Type::Record:
2450 case Type::Enum:
2451 case Type::UnresolvedUsing:
2452 case Type::TypeOfExpr:
2453 case Type::TypeOf:
2454 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002455 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002456 case Type::DependentName:
2457 case Type::InjectedClassName:
2458 case Type::TemplateSpecialization:
2459 case Type::DependentTemplateSpecialization:
2460 case Type::TemplateTypeParm:
2461 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002462 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002463 case Type::PackExpansion:
2464 llvm_unreachable("type should never be variably-modified");
2465
2466 // These types can be variably-modified but should never need to
2467 // further decay.
2468 case Type::FunctionNoProto:
2469 case Type::FunctionProto:
2470 case Type::BlockPointer:
2471 case Type::MemberPointer:
2472 return type;
2473
2474 // These types can be variably-modified. All these modifications
2475 // preserve structure except as noted by comments.
2476 // TODO: if we ever care about optimizing VLAs, there are no-op
2477 // optimizations available here.
2478 case Type::Pointer:
2479 result = getPointerType(getVariableArrayDecayedType(
2480 cast<PointerType>(ty)->getPointeeType()));
2481 break;
2482
2483 case Type::LValueReference: {
2484 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2485 result = getLValueReferenceType(
2486 getVariableArrayDecayedType(lv->getPointeeType()),
2487 lv->isSpelledAsLValue());
2488 break;
2489 }
2490
2491 case Type::RValueReference: {
2492 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2493 result = getRValueReferenceType(
2494 getVariableArrayDecayedType(lv->getPointeeType()));
2495 break;
2496 }
2497
Eli Friedman0dfb8892011-10-06 23:00:33 +00002498 case Type::Atomic: {
2499 const AtomicType *at = cast<AtomicType>(ty);
2500 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2501 break;
2502 }
2503
John McCall06549462011-01-18 08:40:38 +00002504 case Type::ConstantArray: {
2505 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2506 result = getConstantArrayType(
2507 getVariableArrayDecayedType(cat->getElementType()),
2508 cat->getSize(),
2509 cat->getSizeModifier(),
2510 cat->getIndexTypeCVRQualifiers());
2511 break;
2512 }
2513
2514 case Type::DependentSizedArray: {
2515 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2516 result = getDependentSizedArrayType(
2517 getVariableArrayDecayedType(dat->getElementType()),
2518 dat->getSizeExpr(),
2519 dat->getSizeModifier(),
2520 dat->getIndexTypeCVRQualifiers(),
2521 dat->getBracketsRange());
2522 break;
2523 }
2524
2525 // Turn incomplete types into [*] types.
2526 case Type::IncompleteArray: {
2527 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2528 result = getVariableArrayType(
2529 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002530 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002531 ArrayType::Normal,
2532 iat->getIndexTypeCVRQualifiers(),
2533 SourceRange());
2534 break;
2535 }
2536
2537 // Turn VLA types into [*] types.
2538 case Type::VariableArray: {
2539 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2540 result = getVariableArrayType(
2541 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002542 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002543 ArrayType::Star,
2544 vat->getIndexTypeCVRQualifiers(),
2545 vat->getBracketsRange());
2546 break;
2547 }
2548 }
2549
2550 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002551 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002552}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002553
Steve Naroffcadebd02007-08-30 18:14:25 +00002554/// getVariableArrayType - Returns a non-unique reference to the type for a
2555/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002556QualType ASTContext::getVariableArrayType(QualType EltTy,
2557 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002558 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002559 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002560 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002561 // Since we don't unique expressions, it isn't possible to unique VLA's
2562 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002563 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002564
John McCall33ddac02011-01-19 10:06:00 +00002565 // Be sure to pull qualifiers off the element type.
2566 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2567 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002568 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002569 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002570 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002571 }
2572
John McCall90d1c2d2009-09-24 23:30:46 +00002573 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002574 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002575
2576 VariableArrayTypes.push_back(New);
2577 Types.push_back(New);
2578 return QualType(New, 0);
2579}
2580
Douglas Gregor4619e432008-12-05 23:32:09 +00002581/// getDependentSizedArrayType - Returns a non-unique reference to
2582/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002583/// type.
John McCall33ddac02011-01-19 10:06:00 +00002584QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2585 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002586 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002587 unsigned elementTypeQuals,
2588 SourceRange brackets) const {
2589 assert((!numElements || numElements->isTypeDependent() ||
2590 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002591 "Size must be type- or value-dependent!");
2592
John McCall33ddac02011-01-19 10:06:00 +00002593 // Dependently-sized array types that do not have a specified number
2594 // of elements will have their sizes deduced from a dependent
2595 // initializer. We do no canonicalization here at all, which is okay
2596 // because they can't be used in most locations.
2597 if (!numElements) {
2598 DependentSizedArrayType *newType
2599 = new (*this, TypeAlignment)
2600 DependentSizedArrayType(*this, elementType, QualType(),
2601 numElements, ASM, elementTypeQuals,
2602 brackets);
2603 Types.push_back(newType);
2604 return QualType(newType, 0);
2605 }
2606
2607 // Otherwise, we actually build a new type every time, but we
2608 // also build a canonical type.
2609
2610 SplitQualType canonElementType = getCanonicalType(elementType).split();
2611
Craig Topper36250ad2014-05-12 05:36:57 +00002612 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002613 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002614 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002615 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002616 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002617
John McCall33ddac02011-01-19 10:06:00 +00002618 // Look for an existing type with these properties.
2619 DependentSizedArrayType *canonTy =
2620 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002621
John McCall33ddac02011-01-19 10:06:00 +00002622 // If we don't have one, build one.
2623 if (!canonTy) {
2624 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002625 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002626 QualType(), numElements, ASM, elementTypeQuals,
2627 brackets);
2628 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2629 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002630 }
2631
John McCall33ddac02011-01-19 10:06:00 +00002632 // Apply qualifiers from the element type to the array.
2633 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002634 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002635
John McCall33ddac02011-01-19 10:06:00 +00002636 // If we didn't need extra canonicalization for the element type,
2637 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002638 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002639 return canon;
2640
2641 // Otherwise, we need to build a type which follows the spelling
2642 // of the element type.
2643 DependentSizedArrayType *sugaredType
2644 = new (*this, TypeAlignment)
2645 DependentSizedArrayType(*this, elementType, canon, numElements,
2646 ASM, elementTypeQuals, brackets);
2647 Types.push_back(sugaredType);
2648 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002649}
2650
John McCall33ddac02011-01-19 10:06:00 +00002651QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002652 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002653 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002654 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002655 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002656
Craig Topper36250ad2014-05-12 05:36:57 +00002657 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002658 if (IncompleteArrayType *iat =
2659 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2660 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002661
2662 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002663 // either, so fill in the canonical type field. We also have to pull
2664 // qualifiers off the element type.
2665 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002666
John McCall33ddac02011-01-19 10:06:00 +00002667 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2668 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002669 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002670 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002671 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002672
2673 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002674 IncompleteArrayType *existing =
2675 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2676 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002677 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002678
John McCall33ddac02011-01-19 10:06:00 +00002679 IncompleteArrayType *newType = new (*this, TypeAlignment)
2680 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002681
John McCall33ddac02011-01-19 10:06:00 +00002682 IncompleteArrayTypes.InsertNode(newType, insertPos);
2683 Types.push_back(newType);
2684 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002685}
2686
Steve Naroff91fcddb2007-07-18 18:00:27 +00002687/// getVectorType - Return the unique reference to a vector type of
2688/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002689QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002690 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002691 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002692
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002693 // Check if we've already instantiated a vector of this type.
2694 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002695 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002696
Craig Topper36250ad2014-05-12 05:36:57 +00002697 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002698 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2699 return QualType(VTP, 0);
2700
2701 // If the element type isn't canonical, this won't be a canonical type either,
2702 // so fill in the canonical type field.
2703 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002704 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002705 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002706
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002707 // Get the new insert position for the node we care about.
2708 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002709 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002710 }
John McCall90d1c2d2009-09-24 23:30:46 +00002711 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002712 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002713 VectorTypes.InsertNode(New, InsertPos);
2714 Types.push_back(New);
2715 return QualType(New, 0);
2716}
2717
Nate Begemance4d7fc2008-04-18 23:10:10 +00002718/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002719/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002720QualType
2721ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002722 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002723
Steve Naroff91fcddb2007-07-18 18:00:27 +00002724 // Check if we've already instantiated a vector of this type.
2725 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002726 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002727 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002728 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002729 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2730 return QualType(VTP, 0);
2731
2732 // If the element type isn't canonical, this won't be a canonical type either,
2733 // so fill in the canonical type field.
2734 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002735 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002736 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002737
Steve Naroff91fcddb2007-07-18 18:00:27 +00002738 // Get the new insert position for the node we care about.
2739 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002740 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002741 }
John McCall90d1c2d2009-09-24 23:30:46 +00002742 ExtVectorType *New = new (*this, TypeAlignment)
2743 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002744 VectorTypes.InsertNode(New, InsertPos);
2745 Types.push_back(New);
2746 return QualType(New, 0);
2747}
2748
Jay Foad39c79802011-01-12 09:06:06 +00002749QualType
2750ASTContext::getDependentSizedExtVectorType(QualType vecType,
2751 Expr *SizeExpr,
2752 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002753 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002754 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002755 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002756
Craig Topper36250ad2014-05-12 05:36:57 +00002757 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002758 DependentSizedExtVectorType *Canon
2759 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2760 DependentSizedExtVectorType *New;
2761 if (Canon) {
2762 // We already have a canonical version of this array type; use it as
2763 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002764 New = new (*this, TypeAlignment)
2765 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2766 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002767 } else {
2768 QualType CanonVecTy = getCanonicalType(vecType);
2769 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002770 New = new (*this, TypeAlignment)
2771 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2772 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002773
2774 DependentSizedExtVectorType *CanonCheck
2775 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2776 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2777 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002778 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2779 } else {
2780 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2781 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002782 New = new (*this, TypeAlignment)
2783 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002784 }
2785 }
Mike Stump11289f42009-09-09 15:08:12 +00002786
Douglas Gregor758a8692009-06-17 21:51:59 +00002787 Types.push_back(New);
2788 return QualType(New, 0);
2789}
2790
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002791/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002792///
Jay Foad39c79802011-01-12 09:06:06 +00002793QualType
2794ASTContext::getFunctionNoProtoType(QualType ResultTy,
2795 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002796 const CallingConv CallConv = Info.getCC();
2797
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002798 // Unique functions, to guarantee there is only one function of a particular
2799 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002800 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002801 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002802
Craig Topper36250ad2014-05-12 05:36:57 +00002803 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002804 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002805 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002806 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002807
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002808 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002809 if (!ResultTy.isCanonical()) {
2810 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002811
Chris Lattner47955de2007-01-27 08:37:20 +00002812 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002813 FunctionNoProtoType *NewIP =
2814 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002815 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002816 }
Mike Stump11289f42009-09-09 15:08:12 +00002817
Roman Divacky65b88cd2011-03-01 17:40:53 +00002818 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002819 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002820 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002821 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002822 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002823 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002824}
2825
Douglas Gregorcd780372013-01-17 23:36:45 +00002826/// \brief Determine whether \p T is canonical as the result type of a function.
2827static bool isCanonicalResultType(QualType T) {
2828 return T.isCanonical() &&
2829 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2830 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2831}
2832
Jay Foad39c79802011-01-12 09:06:06 +00002833QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002834ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002835 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002836 size_t NumArgs = ArgArray.size();
2837
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002838 // Unique functions, to guarantee there is only one function of a particular
2839 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002840 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002841 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2842 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002843
Craig Topper36250ad2014-05-12 05:36:57 +00002844 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002845 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002846 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002847 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002848
2849 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002850 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002851 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002852 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002853 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002854 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002855 isCanonical = false;
2856
2857 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002858 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002859 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002860 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002861 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002862 CanonicalArgs.reserve(NumArgs);
2863 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002864 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002865
John McCalldb40c7f2010-12-14 08:05:40 +00002866 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002867 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002868 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002869
Douglas Gregorcd780372013-01-17 23:36:45 +00002870 // Result types do not have ARC lifetime qualifiers.
2871 QualType CanResultTy = getCanonicalType(ResultTy);
2872 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2873 Qualifiers Qs = CanResultTy.getQualifiers();
2874 Qs.removeObjCLifetime();
2875 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2876 }
2877
Jordan Rose5c382722013-03-08 21:51:21 +00002878 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002879
Chris Lattnerfd4de792007-01-27 01:15:32 +00002880 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002881 FunctionProtoType *NewIP =
2882 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002883 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002884 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002885
John McCall31168b02011-06-15 23:02:42 +00002886 // FunctionProtoType objects are allocated with extra bytes after
2887 // them for three variable size arrays at the end:
2888 // - parameter types
2889 // - exception types
2890 // - consumed-arguments flags
2891 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002892 // expression, or information used to resolve the exception
2893 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002894 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002895 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00002896 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2897 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2898 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002899 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00002900 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002901 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00002902 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002903 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002904 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002905 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002906 Size += NumArgs * sizeof(bool);
2907
John McCalldb40c7f2010-12-14 08:05:40 +00002908 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002909 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002910 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002911 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002912 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002913 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002914}
Chris Lattneref51c202006-11-10 07:17:23 +00002915
John McCalle78aac42010-03-10 03:28:59 +00002916#ifndef NDEBUG
2917static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2918 if (!isa<CXXRecordDecl>(D)) return false;
2919 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2920 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2921 return true;
2922 if (RD->getDescribedClassTemplate() &&
2923 !isa<ClassTemplateSpecializationDecl>(RD))
2924 return true;
2925 return false;
2926}
2927#endif
2928
2929/// getInjectedClassNameType - Return the unique reference to the
2930/// injected class name type for the specified templated declaration.
2931QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002932 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002933 assert(NeedsInjectedClassNameType(Decl));
2934 if (Decl->TypeForDecl) {
2935 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002936 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002937 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2938 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2939 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2940 } else {
John McCall424cec92011-01-19 06:33:43 +00002941 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002942 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002943 Decl->TypeForDecl = newType;
2944 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002945 }
2946 return QualType(Decl->TypeForDecl, 0);
2947}
2948
Douglas Gregor83a586e2008-04-13 21:07:44 +00002949/// getTypeDeclType - Return the unique reference to the type for the
2950/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002951QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002952 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002953 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002954
Richard Smithdda56e42011-04-15 14:24:37 +00002955 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002956 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002957
John McCall96f0b5f2010-03-10 06:48:02 +00002958 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2959 "Template type parameter types are always available.");
2960
John McCall81e38502010-02-16 03:57:14 +00002961 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002962 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002963 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002964 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002965 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002966 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002967 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002968 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002969 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002970 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2971 Decl->TypeForDecl = newType;
2972 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002973 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002974 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002975
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002976 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002977}
2978
Chris Lattner32d920b2007-01-26 02:01:53 +00002979/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002980/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002981QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002982ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2983 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002984 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002985
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002986 if (Canonical.isNull())
2987 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002988 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002989 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002990 Decl->TypeForDecl = newType;
2991 Types.push_back(newType);
2992 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002993}
2994
Jay Foad39c79802011-01-12 09:06:06 +00002995QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002996 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2997
Douglas Gregorec9fd132012-01-14 16:38:05 +00002998 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002999 if (PrevDecl->TypeForDecl)
3000 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3001
John McCall424cec92011-01-19 06:33:43 +00003002 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3003 Decl->TypeForDecl = newType;
3004 Types.push_back(newType);
3005 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003006}
3007
Jay Foad39c79802011-01-12 09:06:06 +00003008QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003009 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3010
Douglas Gregorec9fd132012-01-14 16:38:05 +00003011 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003012 if (PrevDecl->TypeForDecl)
3013 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3014
John McCall424cec92011-01-19 06:33:43 +00003015 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3016 Decl->TypeForDecl = newType;
3017 Types.push_back(newType);
3018 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003019}
3020
John McCall81904512011-01-06 01:58:22 +00003021QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3022 QualType modifiedType,
3023 QualType equivalentType) {
3024 llvm::FoldingSetNodeID id;
3025 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3026
Craig Topper36250ad2014-05-12 05:36:57 +00003027 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003028 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3029 if (type) return QualType(type, 0);
3030
3031 QualType canon = getCanonicalType(equivalentType);
3032 type = new (*this, TypeAlignment)
3033 AttributedType(canon, attrKind, modifiedType, equivalentType);
3034
3035 Types.push_back(type);
3036 AttributedTypes.InsertNode(type, insertPos);
3037
3038 return QualType(type, 0);
3039}
3040
3041
John McCallcebee162009-10-18 09:09:24 +00003042/// \brief Retrieve a substitution-result type.
3043QualType
3044ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003045 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003046 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003047 && "replacement types must always be canonical");
3048
3049 llvm::FoldingSetNodeID ID;
3050 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003051 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003052 SubstTemplateTypeParmType *SubstParm
3053 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3054
3055 if (!SubstParm) {
3056 SubstParm = new (*this, TypeAlignment)
3057 SubstTemplateTypeParmType(Parm, Replacement);
3058 Types.push_back(SubstParm);
3059 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3060 }
3061
3062 return QualType(SubstParm, 0);
3063}
3064
Douglas Gregorada4b792011-01-14 02:55:32 +00003065/// \brief Retrieve a
3066QualType ASTContext::getSubstTemplateTypeParmPackType(
3067 const TemplateTypeParmType *Parm,
3068 const TemplateArgument &ArgPack) {
3069#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003070 for (const auto &P : ArgPack.pack_elements()) {
3071 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3072 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003073 }
3074#endif
3075
3076 llvm::FoldingSetNodeID ID;
3077 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003078 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003079 if (SubstTemplateTypeParmPackType *SubstParm
3080 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3081 return QualType(SubstParm, 0);
3082
3083 QualType Canon;
3084 if (!Parm->isCanonicalUnqualified()) {
3085 Canon = getCanonicalType(QualType(Parm, 0));
3086 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3087 ArgPack);
3088 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3089 }
3090
3091 SubstTemplateTypeParmPackType *SubstParm
3092 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3093 ArgPack);
3094 Types.push_back(SubstParm);
3095 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3096 return QualType(SubstParm, 0);
3097}
3098
Douglas Gregoreff93e02009-02-05 23:33:38 +00003099/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003100/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003101/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003102QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003103 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003104 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003105 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003106 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003107 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003108 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003109 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3110
3111 if (TypeParm)
3112 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003113
Chandler Carruth08836322011-05-01 00:51:33 +00003114 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003115 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003116 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003117
3118 TemplateTypeParmType *TypeCheck
3119 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3120 assert(!TypeCheck && "Template type parameter canonical type broken");
3121 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003122 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003123 TypeParm = new (*this, TypeAlignment)
3124 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003125
3126 Types.push_back(TypeParm);
3127 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3128
3129 return QualType(TypeParm, 0);
3130}
3131
John McCalle78aac42010-03-10 03:28:59 +00003132TypeSourceInfo *
3133ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3134 SourceLocation NameLoc,
3135 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003136 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003137 assert(!Name.getAsDependentTemplateName() &&
3138 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003139 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003140
3141 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003142 TemplateSpecializationTypeLoc TL =
3143 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003144 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003145 TL.setTemplateNameLoc(NameLoc);
3146 TL.setLAngleLoc(Args.getLAngleLoc());
3147 TL.setRAngleLoc(Args.getRAngleLoc());
3148 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3149 TL.setArgLocInfo(i, Args[i].getLocInfo());
3150 return DI;
3151}
3152
Mike Stump11289f42009-09-09 15:08:12 +00003153QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003154ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003155 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003156 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003157 assert(!Template.getAsDependentTemplateName() &&
3158 "No dependent template names here!");
3159
John McCall6b51f282009-11-23 01:53:49 +00003160 unsigned NumArgs = Args.size();
3161
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003162 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003163 ArgVec.reserve(NumArgs);
3164 for (unsigned i = 0; i != NumArgs; ++i)
3165 ArgVec.push_back(Args[i].getArgument());
3166
John McCall2408e322010-04-27 00:57:59 +00003167 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003168 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003169}
3170
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003171#ifndef NDEBUG
3172static bool hasAnyPackExpansions(const TemplateArgument *Args,
3173 unsigned NumArgs) {
3174 for (unsigned I = 0; I != NumArgs; ++I)
3175 if (Args[I].isPackExpansion())
3176 return true;
3177
3178 return true;
3179}
3180#endif
3181
John McCall0ad16662009-10-29 08:12:44 +00003182QualType
3183ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003184 const TemplateArgument *Args,
3185 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003186 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003187 assert(!Template.getAsDependentTemplateName() &&
3188 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003189 // Look through qualified template names.
3190 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3191 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003192
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003193 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003194 Template.getAsTemplateDecl() &&
3195 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003196 QualType CanonType;
3197 if (!Underlying.isNull())
3198 CanonType = getCanonicalType(Underlying);
3199 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003200 // We can get here with an alias template when the specialization contains
3201 // a pack expansion that does not match up with a parameter pack.
3202 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3203 "Caller must compute aliased type");
3204 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003205 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3206 NumArgs);
3207 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003208
Douglas Gregora8e02e72009-07-28 23:00:59 +00003209 // Allocate the (non-canonical) template specialization type, but don't
3210 // try to unique it: these types typically have location information that
3211 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003212 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3213 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003214 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003215 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003216 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003217 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3218 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003219
Douglas Gregor8bf42052009-02-09 18:46:07 +00003220 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003221 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003222}
3223
Mike Stump11289f42009-09-09 15:08:12 +00003224QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003225ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3226 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003227 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003228 assert(!Template.getAsDependentTemplateName() &&
3229 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003230
Douglas Gregore29139c2011-03-03 17:04:51 +00003231 // Look through qualified template names.
3232 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3233 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003234
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003235 // Build the canonical template specialization type.
3236 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003237 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003238 CanonArgs.reserve(NumArgs);
3239 for (unsigned I = 0; I != NumArgs; ++I)
3240 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3241
3242 // Determine whether this canonical template specialization type already
3243 // exists.
3244 llvm::FoldingSetNodeID ID;
3245 TemplateSpecializationType::Profile(ID, CanonTemplate,
3246 CanonArgs.data(), NumArgs, *this);
3247
Craig Topper36250ad2014-05-12 05:36:57 +00003248 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003249 TemplateSpecializationType *Spec
3250 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3251
3252 if (!Spec) {
3253 // Allocate a new canonical template specialization type.
3254 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3255 sizeof(TemplateArgument) * NumArgs),
3256 TypeAlignment);
3257 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3258 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003259 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003260 Types.push_back(Spec);
3261 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3262 }
3263
3264 assert(Spec->isDependentType() &&
3265 "Non-dependent template-id type must have a canonical type");
3266 return QualType(Spec, 0);
3267}
3268
3269QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003270ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3271 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003272 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003273 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003274 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003275
Craig Topper36250ad2014-05-12 05:36:57 +00003276 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003277 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003278 if (T)
3279 return QualType(T, 0);
3280
Douglas Gregorc42075a2010-02-04 18:10:26 +00003281 QualType Canon = NamedType;
3282 if (!Canon.isCanonical()) {
3283 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003284 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3285 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003286 (void)CheckT;
3287 }
3288
Abramo Bagnara6150c882010-05-11 21:36:43 +00003289 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003290 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003291 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003292 return QualType(T, 0);
3293}
3294
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003295QualType
Jay Foad39c79802011-01-12 09:06:06 +00003296ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003297 llvm::FoldingSetNodeID ID;
3298 ParenType::Profile(ID, InnerType);
3299
Craig Topper36250ad2014-05-12 05:36:57 +00003300 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003301 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3302 if (T)
3303 return QualType(T, 0);
3304
3305 QualType Canon = InnerType;
3306 if (!Canon.isCanonical()) {
3307 Canon = getCanonicalType(InnerType);
3308 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3309 assert(!CheckT && "Paren canonical type broken");
3310 (void)CheckT;
3311 }
3312
3313 T = new (*this) ParenType(InnerType, Canon);
3314 Types.push_back(T);
3315 ParenTypes.InsertNode(T, InsertPos);
3316 return QualType(T, 0);
3317}
3318
Douglas Gregor02085352010-03-31 20:19:30 +00003319QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3320 NestedNameSpecifier *NNS,
3321 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003322 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003323 if (Canon.isNull()) {
3324 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003325 ElaboratedTypeKeyword CanonKeyword = Keyword;
3326 if (Keyword == ETK_None)
3327 CanonKeyword = ETK_Typename;
3328
3329 if (CanonNNS != NNS || CanonKeyword != Keyword)
3330 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003331 }
3332
3333 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003334 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003335
Craig Topper36250ad2014-05-12 05:36:57 +00003336 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003337 DependentNameType *T
3338 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003339 if (T)
3340 return QualType(T, 0);
3341
Douglas Gregor02085352010-03-31 20:19:30 +00003342 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003343 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003344 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003345 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003346}
3347
Mike Stump11289f42009-09-09 15:08:12 +00003348QualType
John McCallc392f372010-06-11 00:33:02 +00003349ASTContext::getDependentTemplateSpecializationType(
3350 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003351 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003352 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003353 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003354 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003355 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003356 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3357 ArgCopy.push_back(Args[I].getArgument());
3358 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3359 ArgCopy.size(),
3360 ArgCopy.data());
3361}
3362
3363QualType
3364ASTContext::getDependentTemplateSpecializationType(
3365 ElaboratedTypeKeyword Keyword,
3366 NestedNameSpecifier *NNS,
3367 const IdentifierInfo *Name,
3368 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003369 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003370 assert((!NNS || NNS->isDependent()) &&
3371 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003372
Douglas Gregorc42075a2010-02-04 18:10:26 +00003373 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003374 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3375 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003376
Craig Topper36250ad2014-05-12 05:36:57 +00003377 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003378 DependentTemplateSpecializationType *T
3379 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003380 if (T)
3381 return QualType(T, 0);
3382
John McCallc392f372010-06-11 00:33:02 +00003383 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003384
John McCallc392f372010-06-11 00:33:02 +00003385 ElaboratedTypeKeyword CanonKeyword = Keyword;
3386 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3387
3388 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003389 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003390 for (unsigned I = 0; I != NumArgs; ++I) {
3391 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3392 if (!CanonArgs[I].structurallyEquals(Args[I]))
3393 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003394 }
3395
John McCallc392f372010-06-11 00:33:02 +00003396 QualType Canon;
3397 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3398 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3399 Name, NumArgs,
3400 CanonArgs.data());
3401
3402 // Find the insert position again.
3403 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3404 }
3405
3406 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3407 sizeof(TemplateArgument) * NumArgs),
3408 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003409 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003410 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003411 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003412 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003413 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003414}
3415
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003416QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003417 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003418 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003419 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003420
3421 assert(Pattern->containsUnexpandedParameterPack() &&
3422 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003423 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003424 PackExpansionType *T
3425 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3426 if (T)
3427 return QualType(T, 0);
3428
3429 QualType Canon;
3430 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003431 Canon = getCanonicalType(Pattern);
3432 // The canonical type might not contain an unexpanded parameter pack, if it
3433 // contains an alias template specialization which ignores one of its
3434 // parameters.
3435 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003436 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003437
Richard Smith68eea502012-07-16 00:20:35 +00003438 // Find the insert position again, in case we inserted an element into
3439 // PackExpansionTypes and invalidated our insert position.
3440 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3441 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003442 }
3443
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003444 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003445 Types.push_back(T);
3446 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003447 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003448}
3449
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003450/// CmpProtocolNames - Comparison predicate for sorting protocols
3451/// alphabetically.
3452static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3453 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003454 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003455}
3456
John McCall8b07ec22010-05-15 11:32:37 +00003457static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003458 unsigned NumProtocols) {
3459 if (NumProtocols == 0) return true;
3460
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003461 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3462 return false;
3463
John McCallfc93cf92009-10-22 22:37:11 +00003464 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003465 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3466 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003467 return false;
3468 return true;
3469}
3470
3471static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003472 unsigned &NumProtocols) {
3473 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003474
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003475 // Sort protocols, keyed by name.
3476 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3477
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003478 // Canonicalize.
3479 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3480 Protocols[I] = Protocols[I]->getCanonicalDecl();
3481
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003482 // Remove duplicates.
3483 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3484 NumProtocols = ProtocolsEnd-Protocols;
3485}
3486
John McCall8b07ec22010-05-15 11:32:37 +00003487QualType ASTContext::getObjCObjectType(QualType BaseType,
3488 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003489 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003490 // If the base type is an interface and there aren't any protocols
3491 // to add, then the interface type will do just fine.
3492 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3493 return BaseType;
3494
3495 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003496 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003497 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003498 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003499 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3500 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003501
John McCall8b07ec22010-05-15 11:32:37 +00003502 // Build the canonical type, which has the canonical base type and
3503 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003504 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003505 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3506 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3507 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003508 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003509 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003510 unsigned UniqueCount = NumProtocols;
3511
John McCallfc93cf92009-10-22 22:37:11 +00003512 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003513 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3514 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003515 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003516 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3517 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003518 }
3519
3520 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003521 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3522 }
3523
3524 unsigned Size = sizeof(ObjCObjectTypeImpl);
3525 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3526 void *Mem = Allocate(Size, TypeAlignment);
3527 ObjCObjectTypeImpl *T =
3528 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3529
3530 Types.push_back(T);
3531 ObjCObjectTypes.InsertNode(T, InsertPos);
3532 return QualType(T, 0);
3533}
3534
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003535/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3536/// protocol list adopt all protocols in QT's qualified-id protocol
3537/// list.
3538bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3539 ObjCInterfaceDecl *IC) {
3540 if (!QT->isObjCQualifiedIdType())
3541 return false;
3542
3543 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3544 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003545 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003546 if (!IC->ClassImplementsProtocol(Proto, false))
3547 return false;
3548 }
3549 return true;
3550 }
3551 return false;
3552}
3553
3554/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3555/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3556/// of protocols.
3557bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3558 ObjCInterfaceDecl *IDecl) {
3559 if (!QT->isObjCQualifiedIdType())
3560 return false;
3561 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3562 if (!OPT)
3563 return false;
3564 if (!IDecl->hasDefinition())
3565 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003566 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3567 CollectInheritedProtocols(IDecl, InheritedProtocols);
3568 if (InheritedProtocols.empty())
3569 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003570 // Check that if every protocol in list of id<plist> conforms to a protcol
3571 // of IDecl's, then bridge casting is ok.
3572 bool Conforms = false;
3573 for (auto *Proto : OPT->quals()) {
3574 Conforms = false;
3575 for (auto *PI : InheritedProtocols) {
3576 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3577 Conforms = true;
3578 break;
3579 }
3580 }
3581 if (!Conforms)
3582 break;
3583 }
3584 if (Conforms)
3585 return true;
3586
Aaron Ballman83731462014-03-17 16:14:00 +00003587 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003588 // If both the right and left sides have qualifiers.
3589 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003590 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003591 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003592 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003593 break;
3594 }
3595 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003596 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003597 }
3598 return true;
3599}
3600
John McCall8b07ec22010-05-15 11:32:37 +00003601/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3602/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003603QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003604 llvm::FoldingSetNodeID ID;
3605 ObjCObjectPointerType::Profile(ID, ObjectT);
3606
Craig Topper36250ad2014-05-12 05:36:57 +00003607 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003608 if (ObjCObjectPointerType *QT =
3609 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3610 return QualType(QT, 0);
3611
3612 // Find the canonical object type.
3613 QualType Canonical;
3614 if (!ObjectT.isCanonical()) {
3615 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3616
3617 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003618 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3619 }
3620
Douglas Gregorf85bee62010-02-08 22:59:26 +00003621 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003622 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3623 ObjCObjectPointerType *QType =
3624 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003625
Steve Narofffb4330f2009-06-17 22:40:22 +00003626 Types.push_back(QType);
3627 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003628 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003629}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003630
Douglas Gregor1c283312010-08-11 12:19:30 +00003631/// getObjCInterfaceType - Return the unique reference to the type for the
3632/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003633QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3634 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003635 if (Decl->TypeForDecl)
3636 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003637
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003638 if (PrevDecl) {
3639 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3640 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3641 return QualType(PrevDecl->TypeForDecl, 0);
3642 }
3643
Douglas Gregor7671e532011-12-16 16:34:57 +00003644 // Prefer the definition, if there is one.
3645 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3646 Decl = Def;
3647
Douglas Gregor1c283312010-08-11 12:19:30 +00003648 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3649 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3650 Decl->TypeForDecl = T;
3651 Types.push_back(T);
3652 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003653}
3654
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003655/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3656/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003657/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003658/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003659/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003660QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003661 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003662 if (tofExpr->isTypeDependent()) {
3663 llvm::FoldingSetNodeID ID;
3664 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003665
Craig Topper36250ad2014-05-12 05:36:57 +00003666 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003667 DependentTypeOfExprType *Canon
3668 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3669 if (Canon) {
3670 // We already have a "canonical" version of an identical, dependent
3671 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003672 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003673 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003674 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003675 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003676 Canon
3677 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003678 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3679 toe = Canon;
3680 }
3681 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003682 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003683 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003684 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003685 Types.push_back(toe);
3686 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003687}
3688
Steve Naroffa773cd52007-08-01 18:02:17 +00003689/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003690/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003691/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003692/// an issue. This doesn't affect the type checker, since it operates
3693/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003694QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003695 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003696 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003697 Types.push_back(tot);
3698 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003699}
3700
Anders Carlssonad6bd352009-06-24 21:24:56 +00003701
Richard Smith8eb1d322014-06-05 20:13:13 +00003702/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3703/// nodes. This would never be helpful, since each such type has its own
3704/// expression, and would not give a significant memory saving, since there
3705/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003706QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003707 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003708
3709 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003710 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003711 // unique dependent type. Two such decltype-specifiers refer to the same
3712 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003713 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003714 llvm::FoldingSetNodeID ID;
3715 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003716
Craig Topper36250ad2014-05-12 05:36:57 +00003717 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003718 DependentDecltypeType *Canon
3719 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003720 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003721 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003722 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003723 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003724 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003725 dt = new (*this, TypeAlignment)
3726 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003727 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003728 dt = new (*this, TypeAlignment)
3729 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003730 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003731 Types.push_back(dt);
3732 return QualType(dt, 0);
3733}
3734
Alexis Hunte852b102011-05-24 22:41:36 +00003735/// getUnaryTransformationType - We don't unique these, since the memory
3736/// savings are minimal and these are rare.
3737QualType ASTContext::getUnaryTransformType(QualType BaseType,
3738 QualType UnderlyingType,
3739 UnaryTransformType::UTTKind Kind)
3740 const {
3741 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003742 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3743 Kind,
3744 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003745 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003746 Types.push_back(Ty);
3747 return QualType(Ty, 0);
3748}
3749
Richard Smith2a7d4812013-05-04 07:00:32 +00003750/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3751/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3752/// canonical deduced-but-dependent 'auto' type.
3753QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003754 bool IsDependent) const {
3755 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003756 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003757
Richard Smith2a7d4812013-05-04 07:00:32 +00003758 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003759 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003760 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003761 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003762 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3763 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003764
Richard Smith74aeef52013-04-26 16:15:35 +00003765 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003766 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003767 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003768 Types.push_back(AT);
3769 if (InsertPos)
3770 AutoTypes.InsertNode(AT, InsertPos);
3771 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003772}
3773
Eli Friedman0dfb8892011-10-06 23:00:33 +00003774/// getAtomicType - Return the uniqued reference to the atomic type for
3775/// the given value type.
3776QualType ASTContext::getAtomicType(QualType T) const {
3777 // Unique pointers, to guarantee there is only one pointer of a particular
3778 // structure.
3779 llvm::FoldingSetNodeID ID;
3780 AtomicType::Profile(ID, T);
3781
Craig Topper36250ad2014-05-12 05:36:57 +00003782 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003783 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3784 return QualType(AT, 0);
3785
3786 // If the atomic value type isn't canonical, this won't be a canonical type
3787 // either, so fill in the canonical type field.
3788 QualType Canonical;
3789 if (!T.isCanonical()) {
3790 Canonical = getAtomicType(getCanonicalType(T));
3791
3792 // Get the new insert position for the node we care about.
3793 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003794 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003795 }
3796 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3797 Types.push_back(New);
3798 AtomicTypes.InsertNode(New, InsertPos);
3799 return QualType(New, 0);
3800}
3801
Richard Smith02e85f32011-04-14 22:09:26 +00003802/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3803QualType ASTContext::getAutoDeductType() const {
3804 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003805 AutoDeductTy = QualType(
3806 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003807 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003808 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003809 return AutoDeductTy;
3810}
3811
3812/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3813QualType ASTContext::getAutoRRefDeductType() const {
3814 if (AutoRRefDeductTy.isNull())
3815 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3816 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3817 return AutoRRefDeductTy;
3818}
3819
Chris Lattnerfb072462007-01-23 05:45:31 +00003820/// getTagDeclType - Return the unique reference to the type for the
3821/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003822QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003823 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003824 // FIXME: What is the design on getTagDeclType when it requires casting
3825 // away const? mutable?
3826 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003827}
3828
Mike Stump11289f42009-09-09 15:08:12 +00003829/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3830/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3831/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003832CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003833 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003834}
Chris Lattnerfb072462007-01-23 05:45:31 +00003835
Hans Wennborg27541db2011-10-27 08:29:09 +00003836/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3837CanQualType ASTContext::getIntMaxType() const {
3838 return getFromTargetType(Target->getIntMaxType());
3839}
3840
3841/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3842CanQualType ASTContext::getUIntMaxType() const {
3843 return getFromTargetType(Target->getUIntMaxType());
3844}
3845
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003846/// getSignedWCharType - Return the type of "signed wchar_t".
3847/// Used when in C++, as a GCC extension.
3848QualType ASTContext::getSignedWCharType() const {
3849 // FIXME: derive from "Target" ?
3850 return WCharTy;
3851}
3852
3853/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3854/// Used when in C++, as a GCC extension.
3855QualType ASTContext::getUnsignedWCharType() const {
3856 // FIXME: derive from "Target" ?
3857 return UnsignedIntTy;
3858}
3859
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003860QualType ASTContext::getIntPtrType() const {
3861 return getFromTargetType(Target->getIntPtrType());
3862}
3863
3864QualType ASTContext::getUIntPtrType() const {
3865 return getCorrespondingUnsignedType(getIntPtrType());
3866}
3867
Hans Wennborg27541db2011-10-27 08:29:09 +00003868/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003869/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3870QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003871 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003872}
3873
Eli Friedman4e91899e2012-11-27 02:58:24 +00003874/// \brief Return the unique type for "pid_t" defined in
3875/// <sys/types.h>. We need this to compute the correct type for vfork().
3876QualType ASTContext::getProcessIDType() const {
3877 return getFromTargetType(Target->getProcessIDType());
3878}
3879
Chris Lattnera21ad802008-04-02 05:18:44 +00003880//===----------------------------------------------------------------------===//
3881// Type Operators
3882//===----------------------------------------------------------------------===//
3883
Jay Foad39c79802011-01-12 09:06:06 +00003884CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003885 // Push qualifiers into arrays, and then discard any remaining
3886 // qualifiers.
3887 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003888 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003889 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003890 QualType Result;
3891 if (isa<ArrayType>(Ty)) {
3892 Result = getArrayDecayedType(QualType(Ty,0));
3893 } else if (isa<FunctionType>(Ty)) {
3894 Result = getPointerType(QualType(Ty, 0));
3895 } else {
3896 Result = QualType(Ty, 0);
3897 }
3898
3899 return CanQualType::CreateUnsafe(Result);
3900}
3901
John McCall6c9dd522011-01-18 07:41:22 +00003902QualType ASTContext::getUnqualifiedArrayType(QualType type,
3903 Qualifiers &quals) {
3904 SplitQualType splitType = type.getSplitUnqualifiedType();
3905
3906 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3907 // the unqualified desugared type and then drops it on the floor.
3908 // We then have to strip that sugar back off with
3909 // getUnqualifiedDesugaredType(), which is silly.
3910 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003911 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003912
3913 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003914 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003915 quals = splitType.Quals;
3916 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003917 }
3918
John McCall6c9dd522011-01-18 07:41:22 +00003919 // Otherwise, recurse on the array's element type.
3920 QualType elementType = AT->getElementType();
3921 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3922
3923 // If that didn't change the element type, AT has no qualifiers, so we
3924 // can just use the results in splitType.
3925 if (elementType == unqualElementType) {
3926 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003927 quals = splitType.Quals;
3928 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003929 }
3930
3931 // Otherwise, add in the qualifiers from the outermost type, then
3932 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003933 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003934
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003935 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003936 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003937 CAT->getSizeModifier(), 0);
3938 }
3939
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003940 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003941 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003942 }
3943
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003944 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003945 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003946 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003947 VAT->getSizeModifier(),
3948 VAT->getIndexTypeCVRQualifiers(),
3949 VAT->getBracketsRange());
3950 }
3951
3952 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003953 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003954 DSAT->getSizeModifier(), 0,
3955 SourceRange());
3956}
3957
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003958/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3959/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3960/// they point to and return true. If T1 and T2 aren't pointer types
3961/// or pointer-to-member types, or if they are not similar at this
3962/// level, returns false and leaves T1 and T2 unchanged. Top-level
3963/// qualifiers on T1 and T2 are ignored. This function will typically
3964/// be called in a loop that successively "unwraps" pointer and
3965/// pointer-to-member types to compare them at each level.
3966bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3967 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3968 *T2PtrType = T2->getAs<PointerType>();
3969 if (T1PtrType && T2PtrType) {
3970 T1 = T1PtrType->getPointeeType();
3971 T2 = T2PtrType->getPointeeType();
3972 return true;
3973 }
3974
3975 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3976 *T2MPType = T2->getAs<MemberPointerType>();
3977 if (T1MPType && T2MPType &&
3978 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3979 QualType(T2MPType->getClass(), 0))) {
3980 T1 = T1MPType->getPointeeType();
3981 T2 = T2MPType->getPointeeType();
3982 return true;
3983 }
3984
David Blaikiebbafb8a2012-03-11 07:00:24 +00003985 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003986 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3987 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3988 if (T1OPType && T2OPType) {
3989 T1 = T1OPType->getPointeeType();
3990 T2 = T2OPType->getPointeeType();
3991 return true;
3992 }
3993 }
3994
3995 // FIXME: Block pointers, too?
3996
3997 return false;
3998}
3999
Jay Foad39c79802011-01-12 09:06:06 +00004000DeclarationNameInfo
4001ASTContext::getNameForTemplate(TemplateName Name,
4002 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004003 switch (Name.getKind()) {
4004 case TemplateName::QualifiedTemplate:
4005 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004006 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004007 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4008 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004009
John McCalld9dfe3a2011-06-30 08:33:18 +00004010 case TemplateName::OverloadedTemplate: {
4011 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4012 // DNInfo work in progress: CHECKME: what about DNLoc?
4013 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4014 }
4015
4016 case TemplateName::DependentTemplate: {
4017 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004018 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004019 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004020 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4021 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004022 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004023 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4024 // DNInfo work in progress: FIXME: source locations?
4025 DeclarationNameLoc DNLoc;
4026 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4027 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4028 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004029 }
4030 }
4031
John McCalld9dfe3a2011-06-30 08:33:18 +00004032 case TemplateName::SubstTemplateTemplateParm: {
4033 SubstTemplateTemplateParmStorage *subst
4034 = Name.getAsSubstTemplateTemplateParm();
4035 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4036 NameLoc);
4037 }
4038
4039 case TemplateName::SubstTemplateTemplateParmPack: {
4040 SubstTemplateTemplateParmPackStorage *subst
4041 = Name.getAsSubstTemplateTemplateParmPack();
4042 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4043 NameLoc);
4044 }
4045 }
4046
4047 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004048}
4049
Jay Foad39c79802011-01-12 09:06:06 +00004050TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004051 switch (Name.getKind()) {
4052 case TemplateName::QualifiedTemplate:
4053 case TemplateName::Template: {
4054 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004055 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004056 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004057 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4058
4059 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004060 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004061 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004062
John McCalld9dfe3a2011-06-30 08:33:18 +00004063 case TemplateName::OverloadedTemplate:
4064 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004065
John McCalld9dfe3a2011-06-30 08:33:18 +00004066 case TemplateName::DependentTemplate: {
4067 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4068 assert(DTN && "Non-dependent template names must refer to template decls.");
4069 return DTN->CanonicalTemplateName;
4070 }
4071
4072 case TemplateName::SubstTemplateTemplateParm: {
4073 SubstTemplateTemplateParmStorage *subst
4074 = Name.getAsSubstTemplateTemplateParm();
4075 return getCanonicalTemplateName(subst->getReplacement());
4076 }
4077
4078 case TemplateName::SubstTemplateTemplateParmPack: {
4079 SubstTemplateTemplateParmPackStorage *subst
4080 = Name.getAsSubstTemplateTemplateParmPack();
4081 TemplateTemplateParmDecl *canonParameter
4082 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4083 TemplateArgument canonArgPack
4084 = getCanonicalTemplateArgument(subst->getArgumentPack());
4085 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4086 }
4087 }
4088
4089 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004090}
4091
Douglas Gregoradee3e32009-11-11 23:06:43 +00004092bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4093 X = getCanonicalTemplateName(X);
4094 Y = getCanonicalTemplateName(Y);
4095 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4096}
4097
Mike Stump11289f42009-09-09 15:08:12 +00004098TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004099ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004100 switch (Arg.getKind()) {
4101 case TemplateArgument::Null:
4102 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004103
Douglas Gregora8e02e72009-07-28 23:00:59 +00004104 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004105 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004106
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004107 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004108 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4109 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004110 }
Mike Stump11289f42009-09-09 15:08:12 +00004111
Eli Friedmanb826a002012-09-26 02:36:12 +00004112 case TemplateArgument::NullPtr:
4113 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4114 /*isNullPtr*/true);
4115
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004116 case TemplateArgument::Template:
4117 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004118
4119 case TemplateArgument::TemplateExpansion:
4120 return TemplateArgument(getCanonicalTemplateName(
4121 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004122 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004123
Douglas Gregora8e02e72009-07-28 23:00:59 +00004124 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004125 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004126
Douglas Gregora8e02e72009-07-28 23:00:59 +00004127 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004128 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004129
Douglas Gregora8e02e72009-07-28 23:00:59 +00004130 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004131 if (Arg.pack_size() == 0)
4132 return Arg;
4133
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004134 TemplateArgument *CanonArgs
4135 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004136 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004137 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004138 AEnd = Arg.pack_end();
4139 A != AEnd; (void)++A, ++Idx)
4140 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004141
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004142 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004143 }
4144 }
4145
4146 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004147 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004148}
4149
Douglas Gregor333489b2009-03-27 23:10:48 +00004150NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004151ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004152 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004153 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004154
4155 switch (NNS->getKind()) {
4156 case NestedNameSpecifier::Identifier:
4157 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004158 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004159 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4160 NNS->getAsIdentifier());
4161
4162 case NestedNameSpecifier::Namespace:
4163 // A namespace is canonical; build a nested-name-specifier with
4164 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004165 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004166 NNS->getAsNamespace()->getOriginalNamespace());
4167
4168 case NestedNameSpecifier::NamespaceAlias:
4169 // A namespace is canonical; build a nested-name-specifier with
4170 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004171 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004172 NNS->getAsNamespaceAlias()->getNamespace()
4173 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004174
4175 case NestedNameSpecifier::TypeSpec:
4176 case NestedNameSpecifier::TypeSpecWithTemplate: {
4177 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004178
4179 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4180 // break it apart into its prefix and identifier, then reconsititute those
4181 // as the canonical nested-name-specifier. This is required to canonicalize
4182 // a dependent nested-name-specifier involving typedefs of dependent-name
4183 // types, e.g.,
4184 // typedef typename T::type T1;
4185 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004186 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4187 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004188 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004189
Eli Friedman5358a0a2012-03-03 04:09:56 +00004190 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4191 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4192 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004193 return NestedNameSpecifier::Create(*this, nullptr, false,
4194 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004195 }
4196
4197 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004198 case NestedNameSpecifier::Super:
4199 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004200 return NNS;
4201 }
4202
David Blaikie8a40f702012-01-17 06:56:22 +00004203 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004204}
4205
Chris Lattner7adf0762008-08-04 07:31:14 +00004206
Jay Foad39c79802011-01-12 09:06:06 +00004207const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004208 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004209 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004210 // Handle the common positive case fast.
4211 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4212 return AT;
4213 }
Mike Stump11289f42009-09-09 15:08:12 +00004214
John McCall8ccfcb52009-09-24 19:53:00 +00004215 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004216 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004217 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004218
John McCall8ccfcb52009-09-24 19:53:00 +00004219 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004220 // implements C99 6.7.3p8: "If the specification of an array type includes
4221 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004222
Chris Lattner7adf0762008-08-04 07:31:14 +00004223 // If we get here, we either have type qualifiers on the type, or we have
4224 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004225 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004226
John McCall33ddac02011-01-19 10:06:00 +00004227 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004228 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004229
Chris Lattner7adf0762008-08-04 07:31:14 +00004230 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004231 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004232 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004233 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004234
Chris Lattner7adf0762008-08-04 07:31:14 +00004235 // Otherwise, we have an array and we have qualifiers on it. Push the
4236 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004237 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004238
Chris Lattner7adf0762008-08-04 07:31:14 +00004239 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4240 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4241 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004242 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004243 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4244 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4245 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004246 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004247
Mike Stump11289f42009-09-09 15:08:12 +00004248 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004249 = dyn_cast<DependentSizedArrayType>(ATy))
4250 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004251 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004252 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004253 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004254 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004255 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004256
Chris Lattner7adf0762008-08-04 07:31:14 +00004257 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004258 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004259 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004260 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004261 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004262 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004263}
4264
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004265QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004266 if (T->isArrayType() || T->isFunctionType())
4267 return getDecayedType(T);
4268 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004269}
4270
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004271QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004272 T = getVariableArrayDecayedType(T);
4273 T = getAdjustedParameterType(T);
4274 return T.getUnqualifiedType();
4275}
4276
Chris Lattnera21ad802008-04-02 05:18:44 +00004277/// getArrayDecayedType - Return the properly qualified result of decaying the
4278/// specified array type to a pointer. This operation is non-trivial when
4279/// handling typedefs etc. The canonical type of "T" must be an array type,
4280/// this returns a pointer to a properly qualified element of the array.
4281///
4282/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004283QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004284 // Get the element type with 'getAsArrayType' so that we don't lose any
4285 // typedefs in the element type of the array. This also handles propagation
4286 // of type qualifiers from the array type into the element type if present
4287 // (C99 6.7.3p8).
4288 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4289 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004290
Chris Lattner7adf0762008-08-04 07:31:14 +00004291 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004292
4293 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004294 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004295}
4296
John McCall33ddac02011-01-19 10:06:00 +00004297QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4298 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004299}
4300
John McCall33ddac02011-01-19 10:06:00 +00004301QualType ASTContext::getBaseElementType(QualType type) const {
4302 Qualifiers qs;
4303 while (true) {
4304 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004305 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004306 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004307
John McCall33ddac02011-01-19 10:06:00 +00004308 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004309 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004310 }
Mike Stump11289f42009-09-09 15:08:12 +00004311
John McCall33ddac02011-01-19 10:06:00 +00004312 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004313}
4314
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004315/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004316uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004317ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4318 uint64_t ElementCount = 1;
4319 do {
4320 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004321 CA = dyn_cast_or_null<ConstantArrayType>(
4322 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004323 } while (CA);
4324 return ElementCount;
4325}
4326
Steve Naroff0af91202007-04-27 21:51:21 +00004327/// getFloatingRank - Return a relative rank for floating point types.
4328/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004329static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004330 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004331 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004332
John McCall9dd450b2009-09-21 23:43:11 +00004333 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4334 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004335 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004336 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004337 case BuiltinType::Float: return FloatRank;
4338 case BuiltinType::Double: return DoubleRank;
4339 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004340 }
4341}
4342
Mike Stump11289f42009-09-09 15:08:12 +00004343/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4344/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004345/// 'typeDomain' is a real floating point or complex type.
4346/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004347QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4348 QualType Domain) const {
4349 FloatingRank EltRank = getFloatingRank(Size);
4350 if (Domain->isComplexType()) {
4351 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004352 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004353 case FloatRank: return FloatComplexTy;
4354 case DoubleRank: return DoubleComplexTy;
4355 case LongDoubleRank: return LongDoubleComplexTy;
4356 }
Steve Naroff0af91202007-04-27 21:51:21 +00004357 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004358
4359 assert(Domain->isRealFloatingType() && "Unknown domain!");
4360 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004361 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004362 case FloatRank: return FloatTy;
4363 case DoubleRank: return DoubleTy;
4364 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004365 }
David Blaikief47fa302012-01-17 02:30:50 +00004366 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004367}
4368
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004369/// getFloatingTypeOrder - Compare the rank of the two specified floating
4370/// point types, ignoring the domain of the type (i.e. 'double' ==
4371/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004372/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004373int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004374 FloatingRank LHSR = getFloatingRank(LHS);
4375 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004376
Chris Lattnerb90739d2008-04-06 23:38:49 +00004377 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004378 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004379 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004380 return 1;
4381 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004382}
4383
Chris Lattner76a00cf2008-04-06 22:59:24 +00004384/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4385/// routine will assert if passed a built-in type that isn't an integer or enum,
4386/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004387unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004388 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004389
Chris Lattner76a00cf2008-04-06 22:59:24 +00004390 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004391 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004392 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004393 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004394 case BuiltinType::Char_S:
4395 case BuiltinType::Char_U:
4396 case BuiltinType::SChar:
4397 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004398 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004399 case BuiltinType::Short:
4400 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004401 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004402 case BuiltinType::Int:
4403 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004404 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004405 case BuiltinType::Long:
4406 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004407 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004408 case BuiltinType::LongLong:
4409 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004410 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004411 case BuiltinType::Int128:
4412 case BuiltinType::UInt128:
4413 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004414 }
4415}
4416
Eli Friedman629ffb92009-08-20 04:21:42 +00004417/// \brief Whether this is a promotable bitfield reference according
4418/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4419///
4420/// \returns the type this bit-field will promote to, or NULL if no
4421/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004422QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004423 if (E->isTypeDependent() || E->isValueDependent())
4424 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004425
4426 // FIXME: We should not do this unless E->refersToBitField() is true. This
4427 // matters in C where getSourceBitField() will find bit-fields for various
4428 // cases where the source expression is not a bit-field designator.
4429
John McCalld25db7e2013-05-06 21:39:12 +00004430 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004431 if (!Field)
4432 return QualType();
4433
4434 QualType FT = Field->getType();
4435
Richard Smithcaf33902011-10-10 18:28:20 +00004436 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004437 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004438 // C++ [conv.prom]p5:
4439 // A prvalue for an integral bit-field can be converted to a prvalue of type
4440 // int if int can represent all the values of the bit-field; otherwise, it
4441 // can be converted to unsigned int if unsigned int can represent all the
4442 // values of the bit-field. If the bit-field is larger yet, no integral
4443 // promotion applies to it.
4444 // C11 6.3.1.1/2:
4445 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4446 // If an int can represent all values of the original type (as restricted by
4447 // the width, for a bit-field), the value is converted to an int; otherwise,
4448 // it is converted to an unsigned int.
4449 //
4450 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4451 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004452 if (BitWidth < IntSize)
4453 return IntTy;
4454
4455 if (BitWidth == IntSize)
4456 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4457
4458 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004459 // like the base type. GCC has some weird bugs in this area that we
4460 // deliberately do not follow (GCC follows a pre-standard resolution to
4461 // C's DR315 which treats bit-width as being part of the type, and this leaks
4462 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004463 return QualType();
4464}
4465
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004466/// getPromotedIntegerType - Returns the type that Promotable will
4467/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4468/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004469QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004470 assert(!Promotable.isNull());
4471 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004472 if (const EnumType *ET = Promotable->getAs<EnumType>())
4473 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004474
4475 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4476 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4477 // (3.9.1) can be converted to a prvalue of the first of the following
4478 // types that can represent all the values of its underlying type:
4479 // int, unsigned int, long int, unsigned long int, long long int, or
4480 // unsigned long long int [...]
4481 // FIXME: Is there some better way to compute this?
4482 if (BT->getKind() == BuiltinType::WChar_S ||
4483 BT->getKind() == BuiltinType::WChar_U ||
4484 BT->getKind() == BuiltinType::Char16 ||
4485 BT->getKind() == BuiltinType::Char32) {
4486 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4487 uint64_t FromSize = getTypeSize(BT);
4488 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4489 LongLongTy, UnsignedLongLongTy };
4490 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4491 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4492 if (FromSize < ToSize ||
4493 (FromSize == ToSize &&
4494 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4495 return PromoteTypes[Idx];
4496 }
4497 llvm_unreachable("char type should fit into long long");
4498 }
4499 }
4500
4501 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004502 if (Promotable->isSignedIntegerType())
4503 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004504 uint64_t PromotableSize = getIntWidth(Promotable);
4505 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004506 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4507 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4508}
4509
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004510/// \brief Recurses in pointer/array types until it finds an objc retainable
4511/// type and returns its ownership.
4512Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4513 while (!T.isNull()) {
4514 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4515 return T.getObjCLifetime();
4516 if (T->isArrayType())
4517 T = getBaseElementType(T);
4518 else if (const PointerType *PT = T->getAs<PointerType>())
4519 T = PT->getPointeeType();
4520 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004521 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004522 else
4523 break;
4524 }
4525
4526 return Qualifiers::OCL_None;
4527}
4528
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004529static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4530 // Incomplete enum types are not treated as integer types.
4531 // FIXME: In C++, enum types are never integer types.
4532 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4533 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004534 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004535}
4536
Mike Stump11289f42009-09-09 15:08:12 +00004537/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004538/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004539/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004540int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004541 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4542 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004543
4544 // Unwrap enums to their underlying type.
4545 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4546 LHSC = getIntegerTypeForEnum(ET);
4547 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4548 RHSC = getIntegerTypeForEnum(ET);
4549
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004550 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004551
Chris Lattner76a00cf2008-04-06 22:59:24 +00004552 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4553 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004554
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004555 unsigned LHSRank = getIntegerRank(LHSC);
4556 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004557
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004558 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4559 if (LHSRank == RHSRank) return 0;
4560 return LHSRank > RHSRank ? 1 : -1;
4561 }
Mike Stump11289f42009-09-09 15:08:12 +00004562
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004563 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4564 if (LHSUnsigned) {
4565 // If the unsigned [LHS] type is larger, return it.
4566 if (LHSRank >= RHSRank)
4567 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004568
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004569 // If the signed type can represent all values of the unsigned type, it
4570 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004571 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004572 return -1;
4573 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004574
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004575 // If the unsigned [RHS] type is larger, return it.
4576 if (RHSRank >= LHSRank)
4577 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004578
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004579 // If the signed type can represent all values of the unsigned type, it
4580 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004581 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004582 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004583}
Anders Carlsson98f07902007-08-17 05:31:46 +00004584
Mike Stump11289f42009-09-09 15:08:12 +00004585// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004586QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004587 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004588 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004589 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004590
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004591 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004592
Anders Carlsson98f07902007-08-17 05:31:46 +00004593 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004594 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004595 // int flags;
4596 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004597 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004598 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004599 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004600 FieldTypes[3] = LongTy;
4601
Anders Carlsson98f07902007-08-17 05:31:46 +00004602 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004603 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004604 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004605 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004606 SourceLocation(), nullptr,
4607 FieldTypes[i], /*TInfo=*/nullptr,
4608 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004609 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004610 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004611 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004612 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004613 }
4614
Douglas Gregord5058122010-02-11 01:19:42 +00004615 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004616 }
Mike Stump11289f42009-09-09 15:08:12 +00004617
Anders Carlsson98f07902007-08-17 05:31:46 +00004618 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004619}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004620
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004621QualType ASTContext::getObjCSuperType() const {
4622 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004623 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004624 TUDecl->addDecl(ObjCSuperTypeDecl);
4625 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4626 }
4627 return ObjCSuperType;
4628}
4629
Douglas Gregor512b0772009-04-23 22:29:11 +00004630void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004631 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004632 assert(Rec && "Invalid CFConstantStringType");
4633 CFConstantStringTypeDecl = Rec->getDecl();
4634}
4635
Jay Foad39c79802011-01-12 09:06:06 +00004636QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004637 if (BlockDescriptorType)
4638 return getTagDeclType(BlockDescriptorType);
4639
Alp Toker2dea15b2013-12-17 01:22:38 +00004640 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004641 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004642 RD = buildImplicitRecord("__block_descriptor");
4643 RD->startDefinition();
4644
Mike Stumpd0153282009-10-20 02:12:22 +00004645 QualType FieldTypes[] = {
4646 UnsignedLongTy,
4647 UnsignedLongTy,
4648 };
4649
Craig Topperd6d31ac2013-07-15 08:24:27 +00004650 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004651 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004652 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004653 };
4654
4655 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004656 FieldDecl *Field = FieldDecl::Create(
4657 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004658 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4659 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004660 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004661 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004662 }
4663
Alp Toker2dea15b2013-12-17 01:22:38 +00004664 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004665
Alp Toker2dea15b2013-12-17 01:22:38 +00004666 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004667
4668 return getTagDeclType(BlockDescriptorType);
4669}
4670
Jay Foad39c79802011-01-12 09:06:06 +00004671QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004672 if (BlockDescriptorExtendedType)
4673 return getTagDeclType(BlockDescriptorExtendedType);
4674
Alp Toker2dea15b2013-12-17 01:22:38 +00004675 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004676 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004677 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4678 RD->startDefinition();
4679
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004680 QualType FieldTypes[] = {
4681 UnsignedLongTy,
4682 UnsignedLongTy,
4683 getPointerType(VoidPtrTy),
4684 getPointerType(VoidPtrTy)
4685 };
4686
Craig Topperd6d31ac2013-07-15 08:24:27 +00004687 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004688 "reserved",
4689 "Size",
4690 "CopyFuncPtr",
4691 "DestroyFuncPtr"
4692 };
4693
4694 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004695 FieldDecl *Field = FieldDecl::Create(
4696 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004697 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4698 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004699 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004700 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004701 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004702 }
4703
Alp Toker2dea15b2013-12-17 01:22:38 +00004704 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004705
Alp Toker2dea15b2013-12-17 01:22:38 +00004706 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004707 return getTagDeclType(BlockDescriptorExtendedType);
4708}
4709
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004710/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4711/// requires copy/dispose. Note that this must match the logic
4712/// in buildByrefHelpers.
4713bool ASTContext::BlockRequiresCopying(QualType Ty,
4714 const VarDecl *D) {
4715 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4716 const Expr *copyExpr = getBlockVarCopyInits(D);
4717 if (!copyExpr && record->hasTrivialDestructor()) return false;
4718
Mike Stump94967902009-10-21 18:16:27 +00004719 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004720 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004721
4722 if (!Ty->isObjCRetainableType()) return false;
4723
4724 Qualifiers qs = Ty.getQualifiers();
4725
4726 // If we have lifetime, that dominates.
4727 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4728 assert(getLangOpts().ObjCAutoRefCount);
4729
4730 switch (lifetime) {
4731 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4732
4733 // These are just bits as far as the runtime is concerned.
4734 case Qualifiers::OCL_ExplicitNone:
4735 case Qualifiers::OCL_Autoreleasing:
4736 return false;
4737
4738 // Tell the runtime that this is ARC __weak, called by the
4739 // byref routines.
4740 case Qualifiers::OCL_Weak:
4741 // ARC __strong __block variables need to be retained.
4742 case Qualifiers::OCL_Strong:
4743 return true;
4744 }
4745 llvm_unreachable("fell out of lifetime switch!");
4746 }
4747 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4748 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004749}
4750
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004751bool ASTContext::getByrefLifetime(QualType Ty,
4752 Qualifiers::ObjCLifetime &LifeTime,
4753 bool &HasByrefExtendedLayout) const {
4754
4755 if (!getLangOpts().ObjC1 ||
4756 getLangOpts().getGC() != LangOptions::NonGC)
4757 return false;
4758
4759 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004760 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004761 HasByrefExtendedLayout = true;
4762 LifeTime = Qualifiers::OCL_None;
4763 }
4764 else if (getLangOpts().ObjCAutoRefCount)
4765 LifeTime = Ty.getObjCLifetime();
4766 // MRR.
4767 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4768 LifeTime = Qualifiers::OCL_ExplicitNone;
4769 else
4770 LifeTime = Qualifiers::OCL_None;
4771 return true;
4772}
4773
Douglas Gregorbab8a962011-09-08 01:46:34 +00004774TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4775 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004776 ObjCInstanceTypeDecl =
4777 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004778 return ObjCInstanceTypeDecl;
4779}
4780
Anders Carlsson18acd442007-10-29 06:33:42 +00004781// This returns true if a type has been typedefed to BOOL:
4782// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004783static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004784 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004785 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4786 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004787
Anders Carlssond8499822007-10-29 05:01:08 +00004788 return false;
4789}
4790
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004791/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004792/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004793CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004794 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4795 return CharUnits::Zero();
4796
Ken Dyck40775002010-01-11 17:06:35 +00004797 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004798
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004799 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004800 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004801 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004802 // Treat arrays as pointers, since that's how they're passed in.
4803 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004804 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004805 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004806}
4807
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004808bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4809 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4810 VD->getType()->isIntegralOrEnumerationType() &&
4811 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4812}
4813
Ken Dyck40775002010-01-11 17:06:35 +00004814static inline
4815std::string charUnitsToString(const CharUnits &CU) {
4816 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004817}
4818
John McCall351762c2011-02-07 10:33:21 +00004819/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004820/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004821std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4822 std::string S;
4823
David Chisnall950a9512009-11-17 19:33:30 +00004824 const BlockDecl *Decl = Expr->getBlockDecl();
4825 QualType BlockTy =
4826 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4827 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004828 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004829 getObjCEncodingForMethodParameter(
4830 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4831 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004832 else
Alp Toker314cc812014-01-25 16:55:45 +00004833 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004834 // Compute size of all parameters.
4835 // Start with computing size of a pointer in number of bytes.
4836 // FIXME: There might(should) be a better way of doing this computation!
4837 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004838 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4839 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004840 for (auto PI : Decl->params()) {
4841 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004842 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004843 if (sz.isZero())
4844 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004845 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004846 ParmOffset += sz;
4847 }
4848 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004849 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004850 // Block pointer and offset.
4851 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004852
4853 // Argument types.
4854 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004855 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004856 QualType PType = PVDecl->getOriginalType();
4857 if (const ArrayType *AT =
4858 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4859 // Use array's original type only if it has known number of
4860 // elements.
4861 if (!isa<ConstantArrayType>(AT))
4862 PType = PVDecl->getType();
4863 } else if (PType->isFunctionType())
4864 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004865 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004866 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4867 S, true /*Extended*/);
4868 else
4869 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004870 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004871 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004872 }
John McCall351762c2011-02-07 10:33:21 +00004873
4874 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004875}
4876
Douglas Gregora9d84932011-05-27 01:19:52 +00004877bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004878 std::string& S) {
4879 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004880 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004881 CharUnits ParmOffset;
4882 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004883 for (auto PI : Decl->params()) {
4884 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004885 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004886 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004887 continue;
4888
David Chisnall50e4eba2010-12-30 14:05:53 +00004889 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004890 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004891 ParmOffset += sz;
4892 }
4893 S += charUnitsToString(ParmOffset);
4894 ParmOffset = CharUnits::Zero();
4895
4896 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004897 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004898 QualType PType = PVDecl->getOriginalType();
4899 if (const ArrayType *AT =
4900 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4901 // Use array's original type only if it has known number of
4902 // elements.
4903 if (!isa<ConstantArrayType>(AT))
4904 PType = PVDecl->getType();
4905 } else if (PType->isFunctionType())
4906 PType = PVDecl->getType();
4907 getObjCEncodingForType(PType, S);
4908 S += charUnitsToString(ParmOffset);
4909 ParmOffset += getObjCEncodingTypeSize(PType);
4910 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004911
4912 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004913}
4914
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004915/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4916/// method parameter or return type. If Extended, include class names and
4917/// block object types.
4918void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4919 QualType T, std::string& S,
4920 bool Extended) const {
4921 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4922 getObjCEncodingForTypeQualifier(QT, S);
4923 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00004924 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004925 true /*OutermostType*/,
4926 false /*EncodingProperty*/,
4927 false /*StructField*/,
4928 Extended /*EncodeBlockParameters*/,
4929 Extended /*EncodeClassNames*/);
4930}
4931
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004932/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004933/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004934bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004935 std::string& S,
4936 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004937 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004938 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004939 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4940 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004941 // Compute size of all parameters.
4942 // Start with computing size of a pointer in number of bytes.
4943 // FIXME: There might(should) be a better way of doing this computation!
4944 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004945 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004946 // The first two arguments (self and _cmd) are pointers; account for
4947 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004948 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004949 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004950 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004951 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004952 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004953 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004954 continue;
4955
Ken Dyck40775002010-01-11 17:06:35 +00004956 assert (sz.isPositive() &&
4957 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004958 ParmOffset += sz;
4959 }
Ken Dyck40775002010-01-11 17:06:35 +00004960 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004961 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004962 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004963
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004964 // Argument types.
4965 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004966 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004967 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004968 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004969 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004970 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004971 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4972 // Use array's original type only if it has known number of
4973 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004974 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004975 PType = PVDecl->getType();
4976 } else if (PType->isFunctionType())
4977 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004978 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4979 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004980 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004981 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004982 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004983
4984 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004985}
4986
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004987ObjCPropertyImplDecl *
4988ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4989 const ObjCPropertyDecl *PD,
4990 const Decl *Container) const {
4991 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00004992 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004993 if (const ObjCCategoryImplDecl *CID =
4994 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004995 for (auto *PID : CID->property_impls())
4996 if (PID->getPropertyDecl() == PD)
4997 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00004998 } else {
4999 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5000 for (auto *PID : OID->property_impls())
5001 if (PID->getPropertyDecl() == PD)
5002 return PID;
5003 }
5004 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005005}
5006
Daniel Dunbar4932b362008-08-28 04:38:10 +00005007/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005008/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005009/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5010/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005011/// Property attributes are stored as a comma-delimited C string. The simple
5012/// attributes readonly and bycopy are encoded as single characters. The
5013/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5014/// encoded as single characters, followed by an identifier. Property types
5015/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005016/// these attributes are defined by the following enumeration:
5017/// @code
5018/// enum PropertyAttributes {
5019/// kPropertyReadOnly = 'R', // property is read-only.
5020/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5021/// kPropertyByref = '&', // property is a reference to the value last assigned
5022/// kPropertyDynamic = 'D', // property is dynamic
5023/// kPropertyGetter = 'G', // followed by getter selector name
5024/// kPropertySetter = 'S', // followed by setter selector name
5025/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005026/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005027/// kPropertyWeak = 'W' // 'weak' property
5028/// kPropertyStrong = 'P' // property GC'able
5029/// kPropertyNonAtomic = 'N' // property non-atomic
5030/// };
5031/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005032void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005033 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005034 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005035 // Collect information from the property implementation decl(s).
5036 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005037 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005038
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005039 if (ObjCPropertyImplDecl *PropertyImpDecl =
5040 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5041 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5042 Dynamic = true;
5043 else
5044 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005045 }
5046
5047 // FIXME: This is not very efficient.
5048 S = "T";
5049
5050 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005051 // GCC has some special rules regarding encoding of properties which
5052 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005053 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005054
5055 if (PD->isReadOnly()) {
5056 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005057 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5058 S += ",C";
5059 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5060 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005061 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5062 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005063 } else {
5064 switch (PD->getSetterKind()) {
5065 case ObjCPropertyDecl::Assign: break;
5066 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005067 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005068 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005069 }
5070 }
5071
5072 // It really isn't clear at all what this means, since properties
5073 // are "dynamic by default".
5074 if (Dynamic)
5075 S += ",D";
5076
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005077 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5078 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005079
Daniel Dunbar4932b362008-08-28 04:38:10 +00005080 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5081 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005082 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005083 }
5084
5085 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5086 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005087 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005088 }
5089
5090 if (SynthesizePID) {
5091 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5092 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005093 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005094 }
5095
5096 // FIXME: OBJCGC: weak & strong
5097}
5098
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005099/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005100/// Another legacy compatibility encoding: 32-bit longs are encoded as
5101/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005102/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5103///
5104void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005105 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005106 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005107 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005108 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005109 else
Jay Foad39c79802011-01-12 09:06:06 +00005110 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005111 PointeeTy = IntTy;
5112 }
5113 }
5114}
5115
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005116void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005117 const FieldDecl *Field,
5118 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005119 // We follow the behavior of gcc, expanding structures which are
5120 // directly pointed to, and expanding embedded structures. Note that
5121 // these rules are sufficient to prevent recursive encoding of the
5122 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005123 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005124 true /* outermost type */, false, false,
5125 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005126}
5127
Joe Groff98ac7d22014-07-07 22:25:15 +00005128void ASTContext::getObjCEncodingForPropertyType(QualType T,
5129 std::string& S) const {
5130 // Encode result type.
5131 // GCC has some special rules regarding encoding of properties which
5132 // closely resembles encoding of ivars.
5133 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5134 true /* outermost type */,
5135 true /* encoding property */);
5136}
5137
John McCall393a78d2012-12-20 02:45:14 +00005138static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5139 BuiltinType::Kind kind) {
5140 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005141 case BuiltinType::Void: return 'v';
5142 case BuiltinType::Bool: return 'B';
5143 case BuiltinType::Char_U:
5144 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005145 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005146 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005147 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005148 case BuiltinType::UInt: return 'I';
5149 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005150 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005151 case BuiltinType::UInt128: return 'T';
5152 case BuiltinType::ULongLong: return 'Q';
5153 case BuiltinType::Char_S:
5154 case BuiltinType::SChar: return 'c';
5155 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005156 case BuiltinType::WChar_S:
5157 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005158 case BuiltinType::Int: return 'i';
5159 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005160 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005161 case BuiltinType::LongLong: return 'q';
5162 case BuiltinType::Int128: return 't';
5163 case BuiltinType::Float: return 'f';
5164 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005165 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005166 case BuiltinType::NullPtr: return '*'; // like char*
5167
5168 case BuiltinType::Half:
5169 // FIXME: potentially need @encodes for these!
5170 return ' ';
5171
5172 case BuiltinType::ObjCId:
5173 case BuiltinType::ObjCClass:
5174 case BuiltinType::ObjCSel:
5175 llvm_unreachable("@encoding ObjC primitive type");
5176
5177 // OpenCL and placeholder types don't need @encodings.
5178 case BuiltinType::OCLImage1d:
5179 case BuiltinType::OCLImage1dArray:
5180 case BuiltinType::OCLImage1dBuffer:
5181 case BuiltinType::OCLImage2d:
5182 case BuiltinType::OCLImage2dArray:
5183 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005184 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005185 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005186 case BuiltinType::Dependent:
5187#define BUILTIN_TYPE(KIND, ID)
5188#define PLACEHOLDER_TYPE(KIND, ID) \
5189 case BuiltinType::KIND:
5190#include "clang/AST/BuiltinTypes.def"
5191 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005192 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005193 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005194}
5195
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005196static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5197 EnumDecl *Enum = ET->getDecl();
5198
5199 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5200 if (!Enum->isFixed())
5201 return 'i';
5202
5203 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005204 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5205 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005206}
5207
Jay Foad39c79802011-01-12 09:06:06 +00005208static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005209 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005210 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005211 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005212 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5213 // The GNU runtime requires more information; bitfields are encoded as b,
5214 // then the offset (in bits) of the first element, then the type of the
5215 // bitfield, then the size in bits. For example, in this structure:
5216 //
5217 // struct
5218 // {
5219 // int integer;
5220 // int flags:2;
5221 // };
5222 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5223 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5224 // information is not especially sensible, but we're stuck with it for
5225 // compatibility with GCC, although providing it breaks anything that
5226 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005227 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005228 const RecordDecl *RD = FD->getParent();
5229 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005230 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005231 if (const EnumType *ET = T->getAs<EnumType>())
5232 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005233 else {
5234 const BuiltinType *BT = T->castAs<BuiltinType>();
5235 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5236 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005237 }
Richard Smithcaf33902011-10-10 18:28:20 +00005238 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005239}
5240
Daniel Dunbar07d07852009-10-18 21:17:35 +00005241// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005242void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5243 bool ExpandPointedToStructures,
5244 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005245 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005246 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005247 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005248 bool StructField,
5249 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005250 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005251 bool EncodePointerToObjCTypedef,
5252 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005253 CanQualType CT = getCanonicalType(T);
5254 switch (CT->getTypeClass()) {
5255 case Type::Builtin:
5256 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005257 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005258 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005259 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5260 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5261 else
5262 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005263 return;
Mike Stump11289f42009-09-09 15:08:12 +00005264
John McCall393a78d2012-12-20 02:45:14 +00005265 case Type::Complex: {
5266 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005267 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005268 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005269 return;
5270 }
John McCall393a78d2012-12-20 02:45:14 +00005271
5272 case Type::Atomic: {
5273 const AtomicType *AT = T->castAs<AtomicType>();
5274 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005275 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005276 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005277 }
John McCall393a78d2012-12-20 02:45:14 +00005278
5279 // encoding for pointer or reference types.
5280 case Type::Pointer:
5281 case Type::LValueReference:
5282 case Type::RValueReference: {
5283 QualType PointeeTy;
5284 if (isa<PointerType>(CT)) {
5285 const PointerType *PT = T->castAs<PointerType>();
5286 if (PT->isObjCSelType()) {
5287 S += ':';
5288 return;
5289 }
5290 PointeeTy = PT->getPointeeType();
5291 } else {
5292 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5293 }
5294
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005295 bool isReadOnly = false;
5296 // For historical/compatibility reasons, the read-only qualifier of the
5297 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5298 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005299 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005300 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005301 if (OutermostType && T.isConstQualified()) {
5302 isReadOnly = true;
5303 S += 'r';
5304 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005305 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005306 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005307 while (P->getAs<PointerType>())
5308 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005309 if (P.isConstQualified()) {
5310 isReadOnly = true;
5311 S += 'r';
5312 }
5313 }
5314 if (isReadOnly) {
5315 // Another legacy compatibility encoding. Some ObjC qualifier and type
5316 // combinations need to be rearranged.
5317 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005318 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005319 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005320 }
Mike Stump11289f42009-09-09 15:08:12 +00005321
Anders Carlssond8499822007-10-29 05:01:08 +00005322 if (PointeeTy->isCharType()) {
5323 // char pointer types should be encoded as '*' unless it is a
5324 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005325 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005326 S += '*';
5327 return;
5328 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005329 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005330 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5331 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5332 S += '#';
5333 return;
5334 }
5335 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5336 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5337 S += '@';
5338 return;
5339 }
5340 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005341 }
Anders Carlssond8499822007-10-29 05:01:08 +00005342 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005343 getLegacyIntegralTypeEncoding(PointeeTy);
5344
Mike Stump11289f42009-09-09 15:08:12 +00005345 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005346 nullptr, false, false, false, false, false, false,
5347 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005348 return;
5349 }
John McCall393a78d2012-12-20 02:45:14 +00005350
5351 case Type::ConstantArray:
5352 case Type::IncompleteArray:
5353 case Type::VariableArray: {
5354 const ArrayType *AT = cast<ArrayType>(CT);
5355
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005356 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005357 // Incomplete arrays are encoded as a pointer to the array element.
5358 S += '^';
5359
Mike Stump11289f42009-09-09 15:08:12 +00005360 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005361 false, ExpandStructures, FD);
5362 } else {
5363 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005364
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005365 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5366 S += llvm::utostr(CAT->getSize().getZExtValue());
5367 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005368 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005369 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5370 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005371 S += '0';
5372 }
Mike Stump11289f42009-09-09 15:08:12 +00005373
5374 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005375 false, ExpandStructures, FD,
5376 false, false, false, false, false, false,
5377 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005378 S += ']';
5379 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005380 return;
5381 }
Mike Stump11289f42009-09-09 15:08:12 +00005382
John McCall393a78d2012-12-20 02:45:14 +00005383 case Type::FunctionNoProto:
5384 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005385 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005386 return;
Mike Stump11289f42009-09-09 15:08:12 +00005387
John McCall393a78d2012-12-20 02:45:14 +00005388 case Type::Record: {
5389 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005390 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005391 // Anonymous structures print as '?'
5392 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5393 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005394 if (ClassTemplateSpecializationDecl *Spec
5395 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5396 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005397 llvm::raw_string_ostream OS(S);
5398 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005399 TemplateArgs.data(),
5400 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005401 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005402 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005403 } else {
5404 S += '?';
5405 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005406 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005407 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005408 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005409 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005410 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005411 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005412 if (FD) {
5413 S += '"';
5414 S += Field->getNameAsString();
5415 S += '"';
5416 }
Mike Stump11289f42009-09-09 15:08:12 +00005417
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005418 // Special case bit-fields.
5419 if (Field->isBitField()) {
5420 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005421 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005422 } else {
5423 QualType qt = Field->getType();
5424 getLegacyIntegralTypeEncoding(qt);
5425 getObjCEncodingForTypeImpl(qt, S, false, true,
5426 FD, /*OutermostType*/false,
5427 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005428 /*StructField*/true,
5429 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005430 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005431 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005432 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005433 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005434 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005435 return;
5436 }
Mike Stump11289f42009-09-09 15:08:12 +00005437
John McCall393a78d2012-12-20 02:45:14 +00005438 case Type::BlockPointer: {
5439 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005440 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005441 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005442 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005443
5444 S += '<';
5445 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005446 getObjCEncodingForTypeImpl(
5447 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5448 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005449 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5450 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005451 // Block self
5452 S += "@?";
5453 // Block parameters
5454 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005455 for (const auto &I : FPT->param_types())
5456 getObjCEncodingForTypeImpl(
5457 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5458 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005459 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5460 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005461 }
5462 S += '>';
5463 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005464 return;
5465 }
Mike Stump11289f42009-09-09 15:08:12 +00005466
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005467 case Type::ObjCObject: {
5468 // hack to match legacy encoding of *id and *Class
5469 QualType Ty = getObjCObjectPointerType(CT);
5470 if (Ty->isObjCIdType()) {
5471 S += "{objc_object=}";
5472 return;
5473 }
5474 else if (Ty->isObjCClassType()) {
5475 S += "{objc_class=}";
5476 return;
5477 }
5478 }
5479
John McCall393a78d2012-12-20 02:45:14 +00005480 case Type::ObjCInterface: {
5481 // Ignore protocol qualifiers when mangling at this level.
5482 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005483
John McCall393a78d2012-12-20 02:45:14 +00005484 // The assumption seems to be that this assert will succeed
5485 // because nested levels will have filtered out 'id' and 'Class'.
5486 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005487 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005488 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005489 S += '{';
5490 const IdentifierInfo *II = OI->getIdentifier();
5491 S += II->getName();
5492 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005493 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005494 DeepCollectObjCIvars(OI, true, Ivars);
5495 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005496 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005497 if (Field->isBitField())
5498 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005499 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005500 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5501 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005502 EncodePointerToObjCTypedef,
5503 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005504 }
5505 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005506 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005507 }
Mike Stump11289f42009-09-09 15:08:12 +00005508
John McCall393a78d2012-12-20 02:45:14 +00005509 case Type::ObjCObjectPointer: {
5510 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005511 if (OPT->isObjCIdType()) {
5512 S += '@';
5513 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005514 }
Mike Stump11289f42009-09-09 15:08:12 +00005515
Steve Narofff0c86112009-10-28 22:03:49 +00005516 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5517 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5518 // Since this is a binary compatibility issue, need to consult with runtime
5519 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005520 S += '#';
5521 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005522 }
Mike Stump11289f42009-09-09 15:08:12 +00005523
Chris Lattnere7cabb92009-07-13 00:10:46 +00005524 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005525 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005526 ExpandPointedToStructures,
5527 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005528 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005529 // Note that we do extended encoding of protocol qualifer list
5530 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005531 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005532 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005533 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005534 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005535 S += '>';
5536 }
5537 S += '"';
5538 }
5539 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005540 }
Mike Stump11289f42009-09-09 15:08:12 +00005541
Chris Lattnere7cabb92009-07-13 00:10:46 +00005542 QualType PointeeTy = OPT->getPointeeType();
5543 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005544 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5545 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005546 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005547 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005548 // {...};
5549 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005550 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005551 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005552 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5553 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5554 DeepCollectObjCIvars(OI, true, Ivars);
5555 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5556 if (cast<FieldDecl>(Ivars[i]) == FD) {
5557 S += '{';
5558 S += OI->getIdentifier()->getName();
5559 S += '}';
5560 return;
5561 }
5562 }
5563 }
Mike Stump11289f42009-09-09 15:08:12 +00005564 getObjCEncodingForTypeImpl(PointeeTy, S,
5565 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005566 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005567 false, false, false, false, false,
5568 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005569 return;
5570 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005571
5572 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005573 if (OPT->getInterfaceDecl() &&
5574 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005575 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005576 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005577 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005578 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005579 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005580 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005581 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005582 S += '"';
5583 }
5584 return;
5585 }
Mike Stump11289f42009-09-09 15:08:12 +00005586
John McCalla9e6e8d2010-05-17 23:56:34 +00005587 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005588 // FIXME: we shoul do better than that. 'M' is available.
5589 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005590 // This matches gcc's encoding, even though technically it is insufficient.
5591 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005592 case Type::Vector:
5593 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005594 // Until we have a coherent encoding of these three types, issue warning.
5595 { if (NotEncodedT)
5596 *NotEncodedT = T;
5597 return;
5598 }
5599
5600 // We could see an undeduced auto type here during error recovery.
5601 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005602 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005603 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005604
Richard Smith27d807c2013-04-30 13:56:41 +00005605
John McCall393a78d2012-12-20 02:45:14 +00005606#define ABSTRACT_TYPE(KIND, BASE)
5607#define TYPE(KIND, BASE)
5608#define DEPENDENT_TYPE(KIND, BASE) \
5609 case Type::KIND:
5610#define NON_CANONICAL_TYPE(KIND, BASE) \
5611 case Type::KIND:
5612#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5613 case Type::KIND:
5614#include "clang/AST/TypeNodes.def"
5615 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005616 }
John McCall393a78d2012-12-20 02:45:14 +00005617 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005618}
5619
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005620void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5621 std::string &S,
5622 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005623 bool includeVBases,
5624 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005625 assert(RDecl && "Expected non-null RecordDecl");
5626 assert(!RDecl->isUnion() && "Should not be called for unions");
5627 if (!RDecl->getDefinition())
5628 return;
5629
5630 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5631 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5632 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5633
5634 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005635 for (const auto &BI : CXXRec->bases()) {
5636 if (!BI.isVirtual()) {
5637 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005638 if (base->isEmpty())
5639 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005640 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005641 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5642 std::make_pair(offs, base));
5643 }
5644 }
5645 }
5646
5647 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005648 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005649 uint64_t offs = layout.getFieldOffset(i);
5650 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005651 std::make_pair(offs, Field));
5652 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005653 }
5654
5655 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005656 for (const auto &BI : CXXRec->vbases()) {
5657 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005658 if (base->isEmpty())
5659 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005660 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005661 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5662 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005663 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5664 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005665 }
5666 }
5667
5668 CharUnits size;
5669 if (CXXRec) {
5670 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5671 } else {
5672 size = layout.getSize();
5673 }
5674
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005675#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005676 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005677#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005678 std::multimap<uint64_t, NamedDecl *>::iterator
5679 CurLayObj = FieldOrBaseOffsets.begin();
5680
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005681 if (CXXRec && CXXRec->isDynamicClass() &&
5682 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005683 if (FD) {
5684 S += "\"_vptr$";
5685 std::string recname = CXXRec->getNameAsString();
5686 if (recname.empty()) recname = "?";
5687 S += recname;
5688 S += '"';
5689 }
5690 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005691#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005692 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005693#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005694 }
5695
5696 if (!RDecl->hasFlexibleArrayMember()) {
5697 // Mark the end of the structure.
5698 uint64_t offs = toBits(size);
5699 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005700 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005701 }
5702
5703 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005704#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005705 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005706 if (CurOffs < CurLayObj->first) {
5707 uint64_t padding = CurLayObj->first - CurOffs;
5708 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5709 // packing/alignment of members is different that normal, in which case
5710 // the encoding will be out-of-sync with the real layout.
5711 // If the runtime switches to just consider the size of types without
5712 // taking into account alignment, we could make padding explicit in the
5713 // encoding (e.g. using arrays of chars). The encoding strings would be
5714 // longer then though.
5715 CurOffs += padding;
5716 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005717#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005718
5719 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005720 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005721 break; // reached end of structure.
5722
5723 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5724 // We expand the bases without their virtual bases since those are going
5725 // in the initial structure. Note that this differs from gcc which
5726 // expands virtual bases each time one is encountered in the hierarchy,
5727 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005728 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5729 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005730 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005731#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005732 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005733#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005734 } else {
5735 FieldDecl *field = cast<FieldDecl>(dcl);
5736 if (FD) {
5737 S += '"';
5738 S += field->getNameAsString();
5739 S += '"';
5740 }
5741
5742 if (field->isBitField()) {
5743 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005744#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005745 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005746#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005747 } else {
5748 QualType qt = field->getType();
5749 getLegacyIntegralTypeEncoding(qt);
5750 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5751 /*OutermostType*/false,
5752 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005753 /*StructField*/true,
5754 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005755#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005756 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005757#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005758 }
5759 }
5760 }
5761}
5762
Mike Stump11289f42009-09-09 15:08:12 +00005763void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005764 std::string& S) const {
5765 if (QT & Decl::OBJC_TQ_In)
5766 S += 'n';
5767 if (QT & Decl::OBJC_TQ_Inout)
5768 S += 'N';
5769 if (QT & Decl::OBJC_TQ_Out)
5770 S += 'o';
5771 if (QT & Decl::OBJC_TQ_Bycopy)
5772 S += 'O';
5773 if (QT & Decl::OBJC_TQ_Byref)
5774 S += 'R';
5775 if (QT & Decl::OBJC_TQ_Oneway)
5776 S += 'V';
5777}
5778
Douglas Gregor3ea72692011-08-12 05:46:01 +00005779TypedefDecl *ASTContext::getObjCIdDecl() const {
5780 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005781 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005782 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005783 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005784 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005785 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005786}
5787
Douglas Gregor52e02802011-08-12 06:17:30 +00005788TypedefDecl *ASTContext::getObjCSelDecl() const {
5789 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005790 QualType T = getPointerType(ObjCBuiltinSelTy);
5791 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005792 }
5793 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005794}
5795
Douglas Gregor0a586182011-08-12 05:59:41 +00005796TypedefDecl *ASTContext::getObjCClassDecl() const {
5797 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005798 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005799 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005800 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005801 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005802 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005803}
5804
Douglas Gregord53ae832012-01-17 18:09:05 +00005805ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5806 if (!ObjCProtocolClassDecl) {
5807 ObjCProtocolClassDecl
5808 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5809 SourceLocation(),
5810 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005811 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005812 SourceLocation(), true);
5813 }
5814
5815 return ObjCProtocolClassDecl;
5816}
5817
Meador Inge5d3fb222012-06-16 03:34:49 +00005818//===----------------------------------------------------------------------===//
5819// __builtin_va_list Construction Functions
5820//===----------------------------------------------------------------------===//
5821
5822static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5823 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005824 QualType T = Context->getPointerType(Context->CharTy);
5825 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005826}
5827
5828static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5829 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005830 QualType T = Context->getPointerType(Context->VoidTy);
5831 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005832}
5833
Tim Northover9bb857a2013-01-31 12:13:10 +00005834static TypedefDecl *
5835CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005836 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005837 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005838 if (Context->getLangOpts().CPlusPlus) {
5839 // namespace std { struct __va_list {
5840 NamespaceDecl *NS;
5841 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5842 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005843 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005844 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005845 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005846 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005847 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005848 }
5849
5850 VaListTagDecl->startDefinition();
5851
5852 const size_t NumFields = 5;
5853 QualType FieldTypes[NumFields];
5854 const char *FieldNames[NumFields];
5855
5856 // void *__stack;
5857 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5858 FieldNames[0] = "__stack";
5859
5860 // void *__gr_top;
5861 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5862 FieldNames[1] = "__gr_top";
5863
5864 // void *__vr_top;
5865 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5866 FieldNames[2] = "__vr_top";
5867
5868 // int __gr_offs;
5869 FieldTypes[3] = Context->IntTy;
5870 FieldNames[3] = "__gr_offs";
5871
5872 // int __vr_offs;
5873 FieldTypes[4] = Context->IntTy;
5874 FieldNames[4] = "__vr_offs";
5875
5876 // Create fields
5877 for (unsigned i = 0; i < NumFields; ++i) {
5878 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5879 VaListTagDecl,
5880 SourceLocation(),
5881 SourceLocation(),
5882 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005883 FieldTypes[i], /*TInfo=*/nullptr,
5884 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005885 /*Mutable=*/false,
5886 ICIS_NoInit);
5887 Field->setAccess(AS_public);
5888 VaListTagDecl->addDecl(Field);
5889 }
5890 VaListTagDecl->completeDefinition();
5891 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5892 Context->VaListTagTy = VaListTagType;
5893
5894 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005895 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005896}
5897
Meador Inge5d3fb222012-06-16 03:34:49 +00005898static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5899 // typedef struct __va_list_tag {
5900 RecordDecl *VaListTagDecl;
5901
Alp Toker2dea15b2013-12-17 01:22:38 +00005902 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005903 VaListTagDecl->startDefinition();
5904
5905 const size_t NumFields = 5;
5906 QualType FieldTypes[NumFields];
5907 const char *FieldNames[NumFields];
5908
5909 // unsigned char gpr;
5910 FieldTypes[0] = Context->UnsignedCharTy;
5911 FieldNames[0] = "gpr";
5912
5913 // unsigned char fpr;
5914 FieldTypes[1] = Context->UnsignedCharTy;
5915 FieldNames[1] = "fpr";
5916
5917 // unsigned short reserved;
5918 FieldTypes[2] = Context->UnsignedShortTy;
5919 FieldNames[2] = "reserved";
5920
5921 // void* overflow_arg_area;
5922 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5923 FieldNames[3] = "overflow_arg_area";
5924
5925 // void* reg_save_area;
5926 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5927 FieldNames[4] = "reg_save_area";
5928
5929 // Create fields
5930 for (unsigned i = 0; i < NumFields; ++i) {
5931 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5932 SourceLocation(),
5933 SourceLocation(),
5934 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005935 FieldTypes[i], /*TInfo=*/nullptr,
5936 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00005937 /*Mutable=*/false,
5938 ICIS_NoInit);
5939 Field->setAccess(AS_public);
5940 VaListTagDecl->addDecl(Field);
5941 }
5942 VaListTagDecl->completeDefinition();
5943 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005944 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005945
5946 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005947 TypedefDecl *VaListTagTypedefDecl =
5948 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5949
Meador Inge5d3fb222012-06-16 03:34:49 +00005950 QualType VaListTagTypedefType =
5951 Context->getTypedefType(VaListTagTypedefDecl);
5952
5953 // typedef __va_list_tag __builtin_va_list[1];
5954 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5955 QualType VaListTagArrayType
5956 = Context->getConstantArrayType(VaListTagTypedefType,
5957 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005958 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005959}
5960
5961static TypedefDecl *
5962CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5963 // typedef struct __va_list_tag {
5964 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005965 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005966 VaListTagDecl->startDefinition();
5967
5968 const size_t NumFields = 4;
5969 QualType FieldTypes[NumFields];
5970 const char *FieldNames[NumFields];
5971
5972 // unsigned gp_offset;
5973 FieldTypes[0] = Context->UnsignedIntTy;
5974 FieldNames[0] = "gp_offset";
5975
5976 // unsigned fp_offset;
5977 FieldTypes[1] = Context->UnsignedIntTy;
5978 FieldNames[1] = "fp_offset";
5979
5980 // void* overflow_arg_area;
5981 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5982 FieldNames[2] = "overflow_arg_area";
5983
5984 // void* reg_save_area;
5985 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5986 FieldNames[3] = "reg_save_area";
5987
5988 // Create fields
5989 for (unsigned i = 0; i < NumFields; ++i) {
5990 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5991 VaListTagDecl,
5992 SourceLocation(),
5993 SourceLocation(),
5994 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005995 FieldTypes[i], /*TInfo=*/nullptr,
5996 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00005997 /*Mutable=*/false,
5998 ICIS_NoInit);
5999 Field->setAccess(AS_public);
6000 VaListTagDecl->addDecl(Field);
6001 }
6002 VaListTagDecl->completeDefinition();
6003 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006004 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006005
6006 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006007 TypedefDecl *VaListTagTypedefDecl =
6008 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6009
Meador Inge5d3fb222012-06-16 03:34:49 +00006010 QualType VaListTagTypedefType =
6011 Context->getTypedefType(VaListTagTypedefDecl);
6012
6013 // typedef __va_list_tag __builtin_va_list[1];
6014 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6015 QualType VaListTagArrayType
6016 = Context->getConstantArrayType(VaListTagTypedefType,
6017 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006018 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006019}
6020
6021static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6022 // typedef int __builtin_va_list[4];
6023 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6024 QualType IntArrayType
6025 = Context->getConstantArrayType(Context->IntTy,
6026 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006027 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006028}
6029
Logan Chien57086ce2012-10-10 06:56:20 +00006030static TypedefDecl *
6031CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006032 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006033 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006034 if (Context->getLangOpts().CPlusPlus) {
6035 // namespace std { struct __va_list {
6036 NamespaceDecl *NS;
6037 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6038 Context->getTranslationUnitDecl(),
6039 /*Inline*/false, SourceLocation(),
6040 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006041 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006042 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006043 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006044 }
6045
6046 VaListDecl->startDefinition();
6047
6048 // void * __ap;
6049 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6050 VaListDecl,
6051 SourceLocation(),
6052 SourceLocation(),
6053 &Context->Idents.get("__ap"),
6054 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006055 /*TInfo=*/nullptr,
6056 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006057 /*Mutable=*/false,
6058 ICIS_NoInit);
6059 Field->setAccess(AS_public);
6060 VaListDecl->addDecl(Field);
6061
6062 // };
6063 VaListDecl->completeDefinition();
6064
6065 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006066 QualType T = Context->getRecordType(VaListDecl);
6067 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006068}
6069
Ulrich Weigand47445072013-05-06 16:26:41 +00006070static TypedefDecl *
6071CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6072 // typedef struct __va_list_tag {
6073 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006074 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006075 VaListTagDecl->startDefinition();
6076
6077 const size_t NumFields = 4;
6078 QualType FieldTypes[NumFields];
6079 const char *FieldNames[NumFields];
6080
6081 // long __gpr;
6082 FieldTypes[0] = Context->LongTy;
6083 FieldNames[0] = "__gpr";
6084
6085 // long __fpr;
6086 FieldTypes[1] = Context->LongTy;
6087 FieldNames[1] = "__fpr";
6088
6089 // void *__overflow_arg_area;
6090 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6091 FieldNames[2] = "__overflow_arg_area";
6092
6093 // void *__reg_save_area;
6094 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6095 FieldNames[3] = "__reg_save_area";
6096
6097 // Create fields
6098 for (unsigned i = 0; i < NumFields; ++i) {
6099 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6100 VaListTagDecl,
6101 SourceLocation(),
6102 SourceLocation(),
6103 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006104 FieldTypes[i], /*TInfo=*/nullptr,
6105 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006106 /*Mutable=*/false,
6107 ICIS_NoInit);
6108 Field->setAccess(AS_public);
6109 VaListTagDecl->addDecl(Field);
6110 }
6111 VaListTagDecl->completeDefinition();
6112 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6113 Context->VaListTagTy = VaListTagType;
6114
6115 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006116 TypedefDecl *VaListTagTypedefDecl =
6117 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006118 QualType VaListTagTypedefType =
6119 Context->getTypedefType(VaListTagTypedefDecl);
6120
6121 // typedef __va_list_tag __builtin_va_list[1];
6122 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6123 QualType VaListTagArrayType
6124 = Context->getConstantArrayType(VaListTagTypedefType,
6125 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006126
Alp Toker56b5cc92013-12-15 10:36:26 +00006127 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006128}
6129
Meador Inge5d3fb222012-06-16 03:34:49 +00006130static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6131 TargetInfo::BuiltinVaListKind Kind) {
6132 switch (Kind) {
6133 case TargetInfo::CharPtrBuiltinVaList:
6134 return CreateCharPtrBuiltinVaListDecl(Context);
6135 case TargetInfo::VoidPtrBuiltinVaList:
6136 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006137 case TargetInfo::AArch64ABIBuiltinVaList:
6138 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006139 case TargetInfo::PowerABIBuiltinVaList:
6140 return CreatePowerABIBuiltinVaListDecl(Context);
6141 case TargetInfo::X86_64ABIBuiltinVaList:
6142 return CreateX86_64ABIBuiltinVaListDecl(Context);
6143 case TargetInfo::PNaClABIBuiltinVaList:
6144 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006145 case TargetInfo::AAPCSABIBuiltinVaList:
6146 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006147 case TargetInfo::SystemZBuiltinVaList:
6148 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006149 }
6150
6151 llvm_unreachable("Unhandled __builtin_va_list type kind");
6152}
6153
6154TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006155 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006156 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006157 assert(BuiltinVaListDecl->isImplicit());
6158 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006159
6160 return BuiltinVaListDecl;
6161}
6162
Meador Ingecfb60902012-07-01 15:57:25 +00006163QualType ASTContext::getVaListTagType() const {
6164 // Force the creation of VaListTagTy by building the __builtin_va_list
6165 // declaration.
6166 if (VaListTagTy.isNull())
6167 (void) getBuiltinVaListDecl();
6168
6169 return VaListTagTy;
6170}
6171
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006172void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006173 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006174 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006175
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006176 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006177}
6178
John McCalld28ae272009-12-02 08:04:21 +00006179/// \brief Retrieve the template name that corresponds to a non-empty
6180/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006181TemplateName
6182ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6183 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006184 unsigned size = End - Begin;
6185 assert(size > 1 && "set is not overloaded!");
6186
6187 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6188 size * sizeof(FunctionTemplateDecl*));
6189 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6190
6191 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006192 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006193 NamedDecl *D = *I;
6194 assert(isa<FunctionTemplateDecl>(D) ||
6195 (isa<UsingShadowDecl>(D) &&
6196 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6197 *Storage++ = D;
6198 }
6199
6200 return TemplateName(OT);
6201}
6202
Douglas Gregordc572a32009-03-30 22:58:21 +00006203/// \brief Retrieve the template name that represents a qualified
6204/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006205TemplateName
6206ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6207 bool TemplateKeyword,
6208 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006209 assert(NNS && "Missing nested-name-specifier in qualified template name");
6210
Douglas Gregorc42075a2010-02-04 18:10:26 +00006211 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006212 llvm::FoldingSetNodeID ID;
6213 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6214
Craig Topper36250ad2014-05-12 05:36:57 +00006215 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006216 QualifiedTemplateName *QTN =
6217 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6218 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006219 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6220 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006221 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6222 }
6223
6224 return TemplateName(QTN);
6225}
6226
6227/// \brief Retrieve the template name that represents a dependent
6228/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006229TemplateName
6230ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6231 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006232 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006233 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006234
6235 llvm::FoldingSetNodeID ID;
6236 DependentTemplateName::Profile(ID, NNS, Name);
6237
Craig Topper36250ad2014-05-12 05:36:57 +00006238 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006239 DependentTemplateName *QTN =
6240 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6241
6242 if (QTN)
6243 return TemplateName(QTN);
6244
6245 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6246 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006247 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6248 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006249 } else {
6250 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006251 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6252 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006253 DependentTemplateName *CheckQTN =
6254 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6255 assert(!CheckQTN && "Dependent type name canonicalization broken");
6256 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006257 }
6258
6259 DependentTemplateNames.InsertNode(QTN, InsertPos);
6260 return TemplateName(QTN);
6261}
6262
Douglas Gregor71395fa2009-11-04 00:56:37 +00006263/// \brief Retrieve the template name that represents a dependent
6264/// template name such as \c MetaFun::template operator+.
6265TemplateName
6266ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006267 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006268 assert((!NNS || NNS->isDependent()) &&
6269 "Nested name specifier must be dependent");
6270
6271 llvm::FoldingSetNodeID ID;
6272 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006273
6274 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006275 DependentTemplateName *QTN
6276 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006277
6278 if (QTN)
6279 return TemplateName(QTN);
6280
6281 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6282 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006283 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6284 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006285 } else {
6286 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006287 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6288 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006289
6290 DependentTemplateName *CheckQTN
6291 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6292 assert(!CheckQTN && "Dependent template name canonicalization broken");
6293 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006294 }
6295
6296 DependentTemplateNames.InsertNode(QTN, InsertPos);
6297 return TemplateName(QTN);
6298}
6299
Douglas Gregor5590be02011-01-15 06:45:20 +00006300TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006301ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6302 TemplateName replacement) const {
6303 llvm::FoldingSetNodeID ID;
6304 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006305
6306 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006307 SubstTemplateTemplateParmStorage *subst
6308 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6309
6310 if (!subst) {
6311 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6312 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6313 }
6314
6315 return TemplateName(subst);
6316}
6317
6318TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006319ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6320 const TemplateArgument &ArgPack) const {
6321 ASTContext &Self = const_cast<ASTContext &>(*this);
6322 llvm::FoldingSetNodeID ID;
6323 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006324
6325 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006326 SubstTemplateTemplateParmPackStorage *Subst
6327 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6328
6329 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006330 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006331 ArgPack.pack_size(),
6332 ArgPack.pack_begin());
6333 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6334 }
6335
6336 return TemplateName(Subst);
6337}
6338
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006339/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006340/// TargetInfo, produce the corresponding type. The unsigned @p Type
6341/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006342CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006343 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006344 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006345 case TargetInfo::SignedChar: return SignedCharTy;
6346 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006347 case TargetInfo::SignedShort: return ShortTy;
6348 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6349 case TargetInfo::SignedInt: return IntTy;
6350 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6351 case TargetInfo::SignedLong: return LongTy;
6352 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6353 case TargetInfo::SignedLongLong: return LongLongTy;
6354 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6355 }
6356
David Blaikie83d382b2011-09-23 05:06:16 +00006357 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006358}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006359
6360//===----------------------------------------------------------------------===//
6361// Type Predicates.
6362//===----------------------------------------------------------------------===//
6363
Fariborz Jahanian96207692009-02-18 21:49:28 +00006364/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6365/// garbage collection attribute.
6366///
John McCall553d45a2011-01-12 00:34:59 +00006367Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006368 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006369 return Qualifiers::GCNone;
6370
David Blaikiebbafb8a2012-03-11 07:00:24 +00006371 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006372 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6373
6374 // Default behaviour under objective-C's gc is for ObjC pointers
6375 // (or pointers to them) be treated as though they were declared
6376 // as __strong.
6377 if (GCAttrs == Qualifiers::GCNone) {
6378 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6379 return Qualifiers::Strong;
6380 else if (Ty->isPointerType())
6381 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6382 } else {
6383 // It's not valid to set GC attributes on anything that isn't a
6384 // pointer.
6385#ifndef NDEBUG
6386 QualType CT = Ty->getCanonicalTypeInternal();
6387 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6388 CT = AT->getElementType();
6389 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6390#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006391 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006392 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006393}
6394
Chris Lattner49af6a42008-04-07 06:51:04 +00006395//===----------------------------------------------------------------------===//
6396// Type Compatibility Testing
6397//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006398
Mike Stump11289f42009-09-09 15:08:12 +00006399/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006400/// compatible.
6401static bool areCompatVectorTypes(const VectorType *LHS,
6402 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006403 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006404 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006405 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006406}
6407
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006408bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6409 QualType SecondVec) {
6410 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6411 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6412
6413 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6414 return true;
6415
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006416 // Treat Neon vector types and most AltiVec vector types as if they are the
6417 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006418 const VectorType *First = FirstVec->getAs<VectorType>();
6419 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006420 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006421 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006422 First->getVectorKind() != VectorType::AltiVecPixel &&
6423 First->getVectorKind() != VectorType::AltiVecBool &&
6424 Second->getVectorKind() != VectorType::AltiVecPixel &&
6425 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006426 return true;
6427
6428 return false;
6429}
6430
Steve Naroff8e6aee52009-07-23 01:01:38 +00006431//===----------------------------------------------------------------------===//
6432// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6433//===----------------------------------------------------------------------===//
6434
6435/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6436/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006437bool
6438ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6439 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006440 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006441 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006442 for (auto *PI : rProto->protocols())
6443 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006444 return true;
6445 return false;
6446}
6447
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006448/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6449/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006450bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6451 QualType rhs) {
6452 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6453 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6454 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6455
Aaron Ballman83731462014-03-17 16:14:00 +00006456 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006457 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006458 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006459 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6460 match = true;
6461 break;
6462 }
6463 }
6464 if (!match)
6465 return false;
6466 }
6467 return true;
6468}
6469
Steve Naroff8e6aee52009-07-23 01:01:38 +00006470/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6471/// ObjCQualifiedIDType.
6472bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6473 bool compare) {
6474 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006475 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006476 lhs->isObjCIdType() || lhs->isObjCClassType())
6477 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006478 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006479 rhs->isObjCIdType() || rhs->isObjCClassType())
6480 return true;
6481
6482 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006483 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006484
Steve Naroff8e6aee52009-07-23 01:01:38 +00006485 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006486
Steve Naroff8e6aee52009-07-23 01:01:38 +00006487 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006488 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006489 // make sure we check the class hierarchy.
6490 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006491 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006492 // when comparing an id<P> on lhs with a static type on rhs,
6493 // see if static class implements all of id's protocols, directly or
6494 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006495 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006496 return false;
6497 }
6498 }
6499 // If there are no qualifiers and no interface, we have an 'id'.
6500 return true;
6501 }
Mike Stump11289f42009-09-09 15:08:12 +00006502 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006503 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006504 bool match = false;
6505
6506 // when comparing an id<P> on lhs with a static type on rhs,
6507 // see if static class implements all of id's protocols, directly or
6508 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006509 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006510 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6511 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6512 match = true;
6513 break;
6514 }
6515 }
Mike Stump11289f42009-09-09 15:08:12 +00006516 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006517 // make sure we check the class hierarchy.
6518 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006519 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006520 // when comparing an id<P> on lhs with a static type on rhs,
6521 // see if static class implements all of id's protocols, directly or
6522 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006523 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006524 match = true;
6525 break;
6526 }
6527 }
6528 }
6529 if (!match)
6530 return false;
6531 }
Mike Stump11289f42009-09-09 15:08:12 +00006532
Steve Naroff8e6aee52009-07-23 01:01:38 +00006533 return true;
6534 }
Mike Stump11289f42009-09-09 15:08:12 +00006535
Steve Naroff8e6aee52009-07-23 01:01:38 +00006536 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6537 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6538
Mike Stump11289f42009-09-09 15:08:12 +00006539 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006540 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006541 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006542 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006543 bool match = false;
6544
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006545 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006546 // see if static class implements all of id's protocols, directly or
6547 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006548 // First, lhs protocols in the qualifier list must be found, direct
6549 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006550 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006551 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6552 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6553 match = true;
6554 break;
6555 }
6556 }
6557 if (!match)
6558 return false;
6559 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006560
6561 // Static class's protocols, or its super class or category protocols
6562 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6563 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6564 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6565 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6566 // This is rather dubious but matches gcc's behavior. If lhs has
6567 // no type qualifier and its class has no static protocol(s)
6568 // assume that it is mismatch.
6569 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6570 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006571 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006572 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006573 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006574 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6575 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6576 match = true;
6577 break;
6578 }
6579 }
6580 if (!match)
6581 return false;
6582 }
6583 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006584 return true;
6585 }
6586 return false;
6587}
6588
Eli Friedman47f77112008-08-22 00:56:42 +00006589/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006590/// compatible for assignment from RHS to LHS. This handles validation of any
6591/// protocol qualifiers on the LHS or RHS.
6592///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006593bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6594 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006595 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6596 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6597
Steve Naroff1329fa02009-07-15 18:40:39 +00006598 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006599 if (LHS->isObjCUnqualifiedIdOrClass() ||
6600 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006601 return true;
6602
John McCall8b07ec22010-05-15 11:32:37 +00006603 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006604 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6605 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006606 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006607
6608 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6609 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6610 QualType(RHSOPT,0));
6611
John McCall8b07ec22010-05-15 11:32:37 +00006612 // If we have 2 user-defined types, fall into that path.
6613 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006614 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006615
Steve Naroff8e6aee52009-07-23 01:01:38 +00006616 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006617}
6618
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006619/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006620/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006621/// arguments in block literals. When passed as arguments, passing 'A*' where
6622/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6623/// not OK. For the return type, the opposite is not OK.
6624bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6625 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006626 const ObjCObjectPointerType *RHSOPT,
6627 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006628 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006629 return true;
6630
6631 if (LHSOPT->isObjCBuiltinType()) {
6632 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6633 }
6634
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006635 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006636 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6637 QualType(RHSOPT,0),
6638 false);
6639
6640 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6641 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6642 if (LHS && RHS) { // We have 2 user-defined types.
6643 if (LHS != RHS) {
6644 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006645 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006646 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006647 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006648 }
6649 else
6650 return true;
6651 }
6652 return false;
6653}
6654
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006655/// getIntersectionOfProtocols - This routine finds the intersection of set
6656/// of protocols inherited from two distinct objective-c pointer objects.
6657/// It is used to build composite qualifier list of the composite type of
6658/// the conditional expression involving two objective-c pointer objects.
6659static
6660void getIntersectionOfProtocols(ASTContext &Context,
6661 const ObjCObjectPointerType *LHSOPT,
6662 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006663 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006664
John McCall8b07ec22010-05-15 11:32:37 +00006665 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6666 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6667 assert(LHS->getInterface() && "LHS must have an interface base");
6668 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006669
6670 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6671 unsigned LHSNumProtocols = LHS->getNumProtocols();
6672 if (LHSNumProtocols > 0)
6673 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6674 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006675 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006676 Context.CollectInheritedProtocols(LHS->getInterface(),
6677 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006678 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6679 LHSInheritedProtocols.end());
6680 }
6681
6682 unsigned RHSNumProtocols = RHS->getNumProtocols();
6683 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006684 ObjCProtocolDecl **RHSProtocols =
6685 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006686 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6687 if (InheritedProtocolSet.count(RHSProtocols[i]))
6688 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006689 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006690 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006691 Context.CollectInheritedProtocols(RHS->getInterface(),
6692 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006693 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6694 if (InheritedProtocolSet.count(ProtDecl))
6695 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006696 }
6697}
6698
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006699/// areCommonBaseCompatible - Returns common base class of the two classes if
6700/// one found. Note that this is O'2 algorithm. But it will be called as the
6701/// last type comparison in a ?-exp of ObjC pointer types before a
6702/// warning is issued. So, its invokation is extremely rare.
6703QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006704 const ObjCObjectPointerType *Lptr,
6705 const ObjCObjectPointerType *Rptr) {
6706 const ObjCObjectType *LHS = Lptr->getObjectType();
6707 const ObjCObjectType *RHS = Rptr->getObjectType();
6708 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6709 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006710 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006711 return QualType();
6712
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006713 do {
John McCall8b07ec22010-05-15 11:32:37 +00006714 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006715 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006716 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006717 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6718
6719 QualType Result = QualType(LHS, 0);
6720 if (!Protocols.empty())
6721 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6722 Result = getObjCObjectPointerType(Result);
6723 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006724 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006725 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006726
6727 return QualType();
6728}
6729
John McCall8b07ec22010-05-15 11:32:37 +00006730bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6731 const ObjCObjectType *RHS) {
6732 assert(LHS->getInterface() && "LHS is not an interface type");
6733 assert(RHS->getInterface() && "RHS is not an interface type");
6734
Chris Lattner49af6a42008-04-07 06:51:04 +00006735 // Verify that the base decls are compatible: the RHS must be a subclass of
6736 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006737 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006738 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006739
Chris Lattner49af6a42008-04-07 06:51:04 +00006740 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6741 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006742 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006743 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006744
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006745 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6746 // More detailed analysis is required.
6747 // OK, if LHS is same or a superclass of RHS *and*
6748 // this LHS, or as RHS's super class is assignment compatible with LHS.
6749 bool IsSuperClass =
6750 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6751 if (IsSuperClass) {
6752 // OK if conversion of LHS to SuperClass results in narrowing of types
6753 // ; i.e., SuperClass may implement at least one of the protocols
6754 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6755 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6756 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6757 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6758 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6759 // qualifiers.
6760 for (auto *RHSPI : RHS->quals())
6761 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6762 // If there is no protocols associated with RHS, it is not a match.
6763 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006764 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006765
6766 for (const auto *LHSProto : LHS->quals()) {
6767 bool SuperImplementsProtocol = false;
6768 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6769 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6770 SuperImplementsProtocol = true;
6771 break;
6772 }
6773 if (!SuperImplementsProtocol)
6774 return false;
6775 }
6776 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006777 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006778 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006779}
6780
Steve Naroffb7605152009-02-12 17:52:19 +00006781bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6782 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006783 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6784 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006785
Steve Naroff7cae42b2009-07-10 23:34:53 +00006786 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006787 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006788
6789 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6790 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006791}
6792
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006793bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6794 return canAssignObjCInterfaces(
6795 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6796 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6797}
6798
Mike Stump11289f42009-09-09 15:08:12 +00006799/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006800/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006801/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006802/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006803bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6804 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006805 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006806 return hasSameType(LHS, RHS);
6807
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006808 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006809}
6810
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006811bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006812 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006813}
6814
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006815bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6816 return !mergeTypes(LHS, RHS, true).isNull();
6817}
6818
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006819/// mergeTransparentUnionType - if T is a transparent union type and a member
6820/// of T is compatible with SubType, return the merged type, else return
6821/// QualType()
6822QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6823 bool OfBlockPointer,
6824 bool Unqualified) {
6825 if (const RecordType *UT = T->getAsUnionType()) {
6826 RecordDecl *UD = UT->getDecl();
6827 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006828 for (const auto *I : UD->fields()) {
6829 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006830 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6831 if (!MT.isNull())
6832 return MT;
6833 }
6834 }
6835 }
6836
6837 return QualType();
6838}
6839
Alp Toker9cacbab2014-01-20 20:26:09 +00006840/// mergeFunctionParameterTypes - merge two types which appear as function
6841/// parameter types
6842QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6843 bool OfBlockPointer,
6844 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006845 // GNU extension: two types are compatible if they appear as a function
6846 // argument, one of the types is a transparent union type and the other
6847 // type is compatible with a union member
6848 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6849 Unqualified);
6850 if (!lmerge.isNull())
6851 return lmerge;
6852
6853 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6854 Unqualified);
6855 if (!rmerge.isNull())
6856 return rmerge;
6857
6858 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6859}
6860
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006861QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006862 bool OfBlockPointer,
6863 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006864 const FunctionType *lbase = lhs->getAs<FunctionType>();
6865 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006866 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6867 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006868 bool allLTypes = true;
6869 bool allRTypes = true;
6870
6871 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006872 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006873 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006874 QualType RHS = rbase->getReturnType();
6875 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006876 bool UnqualifiedResult = Unqualified;
6877 if (!UnqualifiedResult)
6878 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006879 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006880 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006881 else
Alp Toker314cc812014-01-25 16:55:45 +00006882 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006883 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006884 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006885
6886 if (Unqualified)
6887 retType = retType.getUnqualifiedType();
6888
Alp Toker314cc812014-01-25 16:55:45 +00006889 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6890 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006891 if (Unqualified) {
6892 LRetType = LRetType.getUnqualifiedType();
6893 RRetType = RRetType.getUnqualifiedType();
6894 }
6895
6896 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006897 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006898 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006899 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006900
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006901 // FIXME: double check this
6902 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6903 // rbase->getRegParmAttr() != 0 &&
6904 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006905 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6906 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006907
Douglas Gregor8c940862010-01-18 17:14:39 +00006908 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006909 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006910 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006911
John McCall8c6b56f2010-12-15 01:06:38 +00006912 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006913 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6914 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006915 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6916 return QualType();
6917
John McCall31168b02011-06-15 23:02:42 +00006918 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6919 return QualType();
6920
John McCall8c6b56f2010-12-15 01:06:38 +00006921 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6922 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006923
Rafael Espindola8778c282012-11-29 16:09:03 +00006924 if (lbaseInfo.getNoReturn() != NoReturn)
6925 allLTypes = false;
6926 if (rbaseInfo.getNoReturn() != NoReturn)
6927 allRTypes = false;
6928
John McCall31168b02011-06-15 23:02:42 +00006929 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006930
Eli Friedman47f77112008-08-22 00:56:42 +00006931 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006932 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6933 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006934 // Compatible functions must have the same number of parameters
6935 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006936 return QualType();
6937
6938 // Variadic and non-variadic functions aren't compatible
6939 if (lproto->isVariadic() != rproto->isVariadic())
6940 return QualType();
6941
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006942 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6943 return QualType();
6944
Fariborz Jahanian97676972011-09-28 21:52:05 +00006945 if (LangOpts.ObjCAutoRefCount &&
6946 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6947 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006948
6949 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006950 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006951 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6952 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6953 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6954 QualType paramType = mergeFunctionParameterTypes(
6955 lParamType, rParamType, OfBlockPointer, Unqualified);
6956 if (paramType.isNull())
6957 return QualType();
6958
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006959 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006960 paramType = paramType.getUnqualifiedType();
6961
6962 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006963 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006964 lParamType = lParamType.getUnqualifiedType();
6965 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006966 }
Alp Toker601b22c2014-01-21 23:35:24 +00006967
6968 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006969 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006970 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006971 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006972 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006973
Eli Friedman47f77112008-08-22 00:56:42 +00006974 if (allLTypes) return lhs;
6975 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006976
6977 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6978 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006979 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006980 }
6981
6982 if (lproto) allRTypes = false;
6983 if (rproto) allLTypes = false;
6984
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006985 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006986 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006987 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006988 if (proto->isVariadic()) return QualType();
6989 // Check that the types are compatible with the types that
6990 // would result from default argument promotions (C99 6.7.5.3p15).
6991 // The only types actually affected are promotable integer
6992 // types and floats, which would be passed as a different
6993 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00006994 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
6995 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00006996
Eli Friedman448ce402012-08-30 00:44:15 +00006997 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006998 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00006999 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7000 paramTy = Enum->getDecl()->getIntegerType();
7001 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007002 return QualType();
7003 }
Alp Toker601b22c2014-01-21 23:35:24 +00007004
7005 if (paramTy->isPromotableIntegerType() ||
7006 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007007 return QualType();
7008 }
7009
7010 if (allLTypes) return lhs;
7011 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007012
7013 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7014 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007015 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007016 }
7017
7018 if (allLTypes) return lhs;
7019 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007020 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007021}
7022
John McCall433c2e62013-03-21 00:10:07 +00007023/// Given that we have an enum type and a non-enum type, try to merge them.
7024static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7025 QualType other, bool isBlockReturnType) {
7026 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7027 // a signed integer type, or an unsigned integer type.
7028 // Compatibility is based on the underlying type, not the promotion
7029 // type.
7030 QualType underlyingType = ET->getDecl()->getIntegerType();
7031 if (underlyingType.isNull()) return QualType();
7032 if (Context.hasSameType(underlyingType, other))
7033 return other;
7034
7035 // In block return types, we're more permissive and accept any
7036 // integral type of the same size.
7037 if (isBlockReturnType && other->isIntegerType() &&
7038 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7039 return other;
7040
7041 return QualType();
7042}
7043
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007044QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007045 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007046 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007047 // C++ [expr]: If an expression initially has the type "reference to T", the
7048 // type is adjusted to "T" prior to any further analysis, the expression
7049 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007050 // expression is an lvalue unless the reference is an rvalue reference and
7051 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007052 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7053 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007054
7055 if (Unqualified) {
7056 LHS = LHS.getUnqualifiedType();
7057 RHS = RHS.getUnqualifiedType();
7058 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007059
Eli Friedman47f77112008-08-22 00:56:42 +00007060 QualType LHSCan = getCanonicalType(LHS),
7061 RHSCan = getCanonicalType(RHS);
7062
7063 // If two types are identical, they are compatible.
7064 if (LHSCan == RHSCan)
7065 return LHS;
7066
John McCall8ccfcb52009-09-24 19:53:00 +00007067 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007068 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7069 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007070 if (LQuals != RQuals) {
7071 // If any of these qualifiers are different, we have a type
7072 // mismatch.
7073 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007074 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7075 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007076 return QualType();
7077
7078 // Exactly one GC qualifier difference is allowed: __strong is
7079 // okay if the other type has no GC qualifier but is an Objective
7080 // C object pointer (i.e. implicitly strong by default). We fix
7081 // this by pretending that the unqualified type was actually
7082 // qualified __strong.
7083 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7084 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7085 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7086
7087 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7088 return QualType();
7089
7090 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7091 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7092 }
7093 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7094 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7095 }
Eli Friedman47f77112008-08-22 00:56:42 +00007096 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007097 }
7098
7099 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007100
Eli Friedmandcca6332009-06-01 01:22:52 +00007101 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7102 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007103
Chris Lattnerfd652912008-01-14 05:45:46 +00007104 // We want to consider the two function types to be the same for these
7105 // comparisons, just force one to the other.
7106 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7107 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007108
7109 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007110 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7111 LHSClass = Type::ConstantArray;
7112 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7113 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007114
John McCall8b07ec22010-05-15 11:32:37 +00007115 // ObjCInterfaces are just specialized ObjCObjects.
7116 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7117 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7118
Nate Begemance4d7fc2008-04-18 23:10:10 +00007119 // Canonicalize ExtVector -> Vector.
7120 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7121 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007122
Chris Lattner95554662008-04-07 05:43:21 +00007123 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007124 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007125 // Note that we only have special rules for turning block enum
7126 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007127 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007128 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007129 }
John McCall9dd450b2009-09-21 23:43:11 +00007130 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007131 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007132 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007133 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007134 if (OfBlockPointer && !BlockReturnType) {
7135 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7136 return LHS;
7137 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7138 return RHS;
7139 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007140
Eli Friedman47f77112008-08-22 00:56:42 +00007141 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007142 }
Eli Friedman47f77112008-08-22 00:56:42 +00007143
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007144 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007145 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007146#define TYPE(Class, Base)
7147#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007148#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007149#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7150#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7151#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007152 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007153
Richard Smith27d807c2013-04-30 13:56:41 +00007154 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007155 case Type::LValueReference:
7156 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007157 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007158 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007159
John McCall8b07ec22010-05-15 11:32:37 +00007160 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007161 case Type::IncompleteArray:
7162 case Type::VariableArray:
7163 case Type::FunctionProto:
7164 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007165 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007166
Chris Lattnerfd652912008-01-14 05:45:46 +00007167 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007168 {
7169 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007170 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7171 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007172 if (Unqualified) {
7173 LHSPointee = LHSPointee.getUnqualifiedType();
7174 RHSPointee = RHSPointee.getUnqualifiedType();
7175 }
7176 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7177 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007178 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007179 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007180 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007181 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007182 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007183 return getPointerType(ResultType);
7184 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007185 case Type::BlockPointer:
7186 {
7187 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007188 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7189 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007190 if (Unqualified) {
7191 LHSPointee = LHSPointee.getUnqualifiedType();
7192 RHSPointee = RHSPointee.getUnqualifiedType();
7193 }
7194 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7195 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007196 if (ResultType.isNull()) return QualType();
7197 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7198 return LHS;
7199 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7200 return RHS;
7201 return getBlockPointerType(ResultType);
7202 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007203 case Type::Atomic:
7204 {
7205 // Merge two pointer types, while trying to preserve typedef info
7206 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7207 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7208 if (Unqualified) {
7209 LHSValue = LHSValue.getUnqualifiedType();
7210 RHSValue = RHSValue.getUnqualifiedType();
7211 }
7212 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7213 Unqualified);
7214 if (ResultType.isNull()) return QualType();
7215 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7216 return LHS;
7217 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7218 return RHS;
7219 return getAtomicType(ResultType);
7220 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007221 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007222 {
7223 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7224 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7225 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7226 return QualType();
7227
7228 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7229 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007230 if (Unqualified) {
7231 LHSElem = LHSElem.getUnqualifiedType();
7232 RHSElem = RHSElem.getUnqualifiedType();
7233 }
7234
7235 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007236 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007237 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7238 return LHS;
7239 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7240 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007241 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7242 ArrayType::ArraySizeModifier(), 0);
7243 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7244 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007245 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7246 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007247 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7248 return LHS;
7249 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7250 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007251 if (LVAT) {
7252 // FIXME: This isn't correct! But tricky to implement because
7253 // the array's size has to be the size of LHS, but the type
7254 // has to be different.
7255 return LHS;
7256 }
7257 if (RVAT) {
7258 // FIXME: This isn't correct! But tricky to implement because
7259 // the array's size has to be the size of RHS, but the type
7260 // has to be different.
7261 return RHS;
7262 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007263 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7264 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007265 return getIncompleteArrayType(ResultType,
7266 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007267 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007268 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007269 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007270 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007271 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007272 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007273 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007274 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007275 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007276 case Type::Complex:
7277 // Distinct complex types are incompatible.
7278 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007279 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007280 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007281 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7282 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007283 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007284 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007285 case Type::ObjCObject: {
7286 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007287 // FIXME: This should be type compatibility, e.g. whether
7288 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007289 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7290 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7291 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007292 return LHS;
7293
Eli Friedman47f77112008-08-22 00:56:42 +00007294 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007295 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007296 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007297 if (OfBlockPointer) {
7298 if (canAssignObjCInterfacesInBlockPointer(
7299 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007300 RHS->getAs<ObjCObjectPointerType>(),
7301 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007302 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007303 return QualType();
7304 }
John McCall9dd450b2009-09-21 23:43:11 +00007305 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7306 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007307 return LHS;
7308
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007309 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007310 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007311 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007312
David Blaikie8a40f702012-01-17 06:56:22 +00007313 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007314}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007315
Fariborz Jahanian97676972011-09-28 21:52:05 +00007316bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7317 const FunctionProtoType *FromFunctionType,
7318 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007319 if (FromFunctionType->hasAnyConsumedParams() !=
7320 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007321 return false;
7322 FunctionProtoType::ExtProtoInfo FromEPI =
7323 FromFunctionType->getExtProtoInfo();
7324 FunctionProtoType::ExtProtoInfo ToEPI =
7325 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007326 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007327 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7328 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007329 return false;
7330 }
7331 return true;
7332}
7333
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007334/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7335/// 'RHS' attributes and returns the merged version; including for function
7336/// return types.
7337QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7338 QualType LHSCan = getCanonicalType(LHS),
7339 RHSCan = getCanonicalType(RHS);
7340 // If two types are identical, they are compatible.
7341 if (LHSCan == RHSCan)
7342 return LHS;
7343 if (RHSCan->isFunctionType()) {
7344 if (!LHSCan->isFunctionType())
7345 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007346 QualType OldReturnType =
7347 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007348 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007349 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007350 QualType ResReturnType =
7351 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7352 if (ResReturnType.isNull())
7353 return QualType();
7354 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7355 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7356 // In either case, use OldReturnType to build the new function type.
7357 const FunctionType *F = LHS->getAs<FunctionType>();
7358 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007359 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7360 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007361 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007362 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007363 return ResultType;
7364 }
7365 }
7366 return QualType();
7367 }
7368
7369 // If the qualifiers are different, the types can still be merged.
7370 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7371 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7372 if (LQuals != RQuals) {
7373 // If any of these qualifiers are different, we have a type mismatch.
7374 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7375 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7376 return QualType();
7377
7378 // Exactly one GC qualifier difference is allowed: __strong is
7379 // okay if the other type has no GC qualifier but is an Objective
7380 // C object pointer (i.e. implicitly strong by default). We fix
7381 // this by pretending that the unqualified type was actually
7382 // qualified __strong.
7383 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7384 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7385 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7386
7387 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7388 return QualType();
7389
7390 if (GC_L == Qualifiers::Strong)
7391 return LHS;
7392 if (GC_R == Qualifiers::Strong)
7393 return RHS;
7394 return QualType();
7395 }
7396
7397 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7398 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7399 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7400 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7401 if (ResQT == LHSBaseQT)
7402 return LHS;
7403 if (ResQT == RHSBaseQT)
7404 return RHS;
7405 }
7406 return QualType();
7407}
7408
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007409//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007410// Integer Predicates
7411//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007412
Jay Foad39c79802011-01-12 09:06:06 +00007413unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007414 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007415 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007416 if (T->isBooleanType())
7417 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007418 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007419 return (unsigned)getTypeSize(T);
7420}
7421
Abramo Bagnara13640492012-09-09 10:21:24 +00007422QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007423 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007424
7425 // Turn <4 x signed int> -> <4 x unsigned int>
7426 if (const VectorType *VTy = T->getAs<VectorType>())
7427 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007428 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007429
7430 // For enums, we return the unsigned version of the base type.
7431 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007432 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007433
7434 const BuiltinType *BTy = T->getAs<BuiltinType>();
7435 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007436 switch (BTy->getKind()) {
7437 case BuiltinType::Char_S:
7438 case BuiltinType::SChar:
7439 return UnsignedCharTy;
7440 case BuiltinType::Short:
7441 return UnsignedShortTy;
7442 case BuiltinType::Int:
7443 return UnsignedIntTy;
7444 case BuiltinType::Long:
7445 return UnsignedLongTy;
7446 case BuiltinType::LongLong:
7447 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007448 case BuiltinType::Int128:
7449 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007450 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007451 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007452 }
7453}
7454
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007455ASTMutationListener::~ASTMutationListener() { }
7456
Richard Smith1fa5d642013-05-11 05:45:24 +00007457void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7458 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007459
7460//===----------------------------------------------------------------------===//
7461// Builtin Type Computation
7462//===----------------------------------------------------------------------===//
7463
7464/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007465/// pointer over the consumed characters. This returns the resultant type. If
7466/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7467/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7468/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007469///
7470/// RequiresICE is filled in on return to indicate whether the value is required
7471/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007472static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007473 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007474 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007475 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007476 // Modifiers.
7477 int HowLong = 0;
7478 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007479 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007480
Chris Lattnerdc226c22010-10-01 22:42:38 +00007481 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007482 bool Done = false;
7483 while (!Done) {
7484 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007485 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007486 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007487 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007488 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007489 case 'S':
7490 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7491 assert(!Signed && "Can't use 'S' modifier multiple times!");
7492 Signed = true;
7493 break;
7494 case 'U':
7495 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7496 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7497 Unsigned = true;
7498 break;
7499 case 'L':
7500 assert(HowLong <= 2 && "Can't have LLLL modifier");
7501 ++HowLong;
7502 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007503 case 'W':
7504 // This modifier represents int64 type.
7505 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7506 switch (Context.getTargetInfo().getInt64Type()) {
7507 default:
7508 llvm_unreachable("Unexpected integer type");
7509 case TargetInfo::SignedLong:
7510 HowLong = 1;
7511 break;
7512 case TargetInfo::SignedLongLong:
7513 HowLong = 2;
7514 break;
7515 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007516 }
7517 }
7518
7519 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007520
Chris Lattnerecd79c62009-06-14 00:45:47 +00007521 // Read the base type.
7522 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007523 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007524 case 'v':
7525 assert(HowLong == 0 && !Signed && !Unsigned &&
7526 "Bad modifiers used with 'v'!");
7527 Type = Context.VoidTy;
7528 break;
Jack Carter24bef982013-08-15 15:16:57 +00007529 case 'h':
7530 assert(HowLong == 0 && !Signed && !Unsigned &&
7531 "Bad modifiers used with 'f'!");
7532 Type = Context.HalfTy;
7533 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007534 case 'f':
7535 assert(HowLong == 0 && !Signed && !Unsigned &&
7536 "Bad modifiers used with 'f'!");
7537 Type = Context.FloatTy;
7538 break;
7539 case 'd':
7540 assert(HowLong < 2 && !Signed && !Unsigned &&
7541 "Bad modifiers used with 'd'!");
7542 if (HowLong)
7543 Type = Context.LongDoubleTy;
7544 else
7545 Type = Context.DoubleTy;
7546 break;
7547 case 's':
7548 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7549 if (Unsigned)
7550 Type = Context.UnsignedShortTy;
7551 else
7552 Type = Context.ShortTy;
7553 break;
7554 case 'i':
7555 if (HowLong == 3)
7556 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7557 else if (HowLong == 2)
7558 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7559 else if (HowLong == 1)
7560 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7561 else
7562 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7563 break;
7564 case 'c':
7565 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7566 if (Signed)
7567 Type = Context.SignedCharTy;
7568 else if (Unsigned)
7569 Type = Context.UnsignedCharTy;
7570 else
7571 Type = Context.CharTy;
7572 break;
7573 case 'b': // boolean
7574 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7575 Type = Context.BoolTy;
7576 break;
7577 case 'z': // size_t.
7578 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7579 Type = Context.getSizeType();
7580 break;
7581 case 'F':
7582 Type = Context.getCFConstantStringType();
7583 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007584 case 'G':
7585 Type = Context.getObjCIdType();
7586 break;
7587 case 'H':
7588 Type = Context.getObjCSelType();
7589 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007590 case 'M':
7591 Type = Context.getObjCSuperType();
7592 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007593 case 'a':
7594 Type = Context.getBuiltinVaListType();
7595 assert(!Type.isNull() && "builtin va list type not initialized!");
7596 break;
7597 case 'A':
7598 // This is a "reference" to a va_list; however, what exactly
7599 // this means depends on how va_list is defined. There are two
7600 // different kinds of va_list: ones passed by value, and ones
7601 // passed by reference. An example of a by-value va_list is
7602 // x86, where va_list is a char*. An example of by-ref va_list
7603 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7604 // we want this argument to be a char*&; for x86-64, we want
7605 // it to be a __va_list_tag*.
7606 Type = Context.getBuiltinVaListType();
7607 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007608 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007609 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007610 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007611 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007612 break;
7613 case 'V': {
7614 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007615 unsigned NumElements = strtoul(Str, &End, 10);
7616 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007617 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007618
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007619 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7620 RequiresICE, false);
7621 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007622
7623 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007624 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007625 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007626 break;
7627 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007628 case 'E': {
7629 char *End;
7630
7631 unsigned NumElements = strtoul(Str, &End, 10);
7632 assert(End != Str && "Missing vector size");
7633
7634 Str = End;
7635
7636 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7637 false);
7638 Type = Context.getExtVectorType(ElementType, NumElements);
7639 break;
7640 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007641 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007642 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7643 false);
7644 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007645 Type = Context.getComplexType(ElementType);
7646 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007647 }
7648 case 'Y' : {
7649 Type = Context.getPointerDiffType();
7650 break;
7651 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007652 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007653 Type = Context.getFILEType();
7654 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007655 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007656 return QualType();
7657 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007658 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007659 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007660 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007661 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007662 else
7663 Type = Context.getjmp_bufType();
7664
Mike Stump2adb4da2009-07-28 23:47:15 +00007665 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007666 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007667 return QualType();
7668 }
7669 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007670 case 'K':
7671 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7672 Type = Context.getucontext_tType();
7673
7674 if (Type.isNull()) {
7675 Error = ASTContext::GE_Missing_ucontext;
7676 return QualType();
7677 }
7678 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007679 case 'p':
7680 Type = Context.getProcessIDType();
7681 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007682 }
Mike Stump11289f42009-09-09 15:08:12 +00007683
Chris Lattnerdc226c22010-10-01 22:42:38 +00007684 // If there are modifiers and if we're allowed to parse them, go for it.
7685 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007686 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007687 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007688 default: Done = true; --Str; break;
7689 case '*':
7690 case '&': {
7691 // Both pointers and references can have their pointee types
7692 // qualified with an address space.
7693 char *End;
7694 unsigned AddrSpace = strtoul(Str, &End, 10);
7695 if (End != Str && AddrSpace != 0) {
7696 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7697 Str = End;
7698 }
7699 if (c == '*')
7700 Type = Context.getPointerType(Type);
7701 else
7702 Type = Context.getLValueReferenceType(Type);
7703 break;
7704 }
7705 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7706 case 'C':
7707 Type = Type.withConst();
7708 break;
7709 case 'D':
7710 Type = Context.getVolatileType(Type);
7711 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007712 case 'R':
7713 Type = Type.withRestrict();
7714 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007715 }
7716 }
Chris Lattner84733392010-10-01 07:13:18 +00007717
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007718 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007719 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007720
Chris Lattnerecd79c62009-06-14 00:45:47 +00007721 return Type;
7722}
7723
7724/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007725QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007726 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007727 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007728 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007729
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007730 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007731
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007732 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007733 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007734 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7735 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007736 if (Error != GE_None)
7737 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007738
7739 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7740
Chris Lattnerecd79c62009-06-14 00:45:47 +00007741 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007742 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007743 if (Error != GE_None)
7744 return QualType();
7745
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007746 // If this argument is required to be an IntegerConstantExpression and the
7747 // caller cares, fill in the bitmask we return.
7748 if (RequiresICE && IntegerConstantArgs)
7749 *IntegerConstantArgs |= 1 << ArgTypes.size();
7750
Chris Lattnerecd79c62009-06-14 00:45:47 +00007751 // Do array -> pointer decay. The builtin should use the decayed type.
7752 if (Ty->isArrayType())
7753 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007754
Chris Lattnerecd79c62009-06-14 00:45:47 +00007755 ArgTypes.push_back(Ty);
7756 }
7757
7758 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7759 "'.' should only occur at end of builtin type list!");
7760
Reid Kleckner78af0702013-08-27 23:08:25 +00007761 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007762 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7763
7764 bool Variadic = (TypeStr[0] == '.');
7765
7766 // We really shouldn't be making a no-proto type here, especially in C++.
7767 if (ArgTypes.empty() && Variadic)
7768 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007769
John McCalldb40c7f2010-12-14 08:05:40 +00007770 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007771 EPI.ExtInfo = EI;
7772 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007773
Jordan Rose5c382722013-03-08 21:51:21 +00007774 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007775}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007776
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007777static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7778 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007779 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007780 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007781
Rafael Espindola3ae00052013-05-13 00:12:11 +00007782 GVALinkage External = GVA_StrongExternal;
7783 switch (FD->getTemplateSpecializationKind()) {
7784 case TSK_Undeclared:
7785 case TSK_ExplicitSpecialization:
7786 External = GVA_StrongExternal;
7787 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007788
Rafael Espindola3ae00052013-05-13 00:12:11 +00007789 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007790 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007791
David Majnemerc3d07332014-05-15 06:25:57 +00007792 // C++11 [temp.explicit]p10:
7793 // [ Note: The intent is that an inline function that is the subject of
7794 // an explicit instantiation declaration will still be implicitly
7795 // instantiated when used so that the body can be considered for
7796 // inlining, but that no out-of-line copy of the inline function would be
7797 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007798 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007799 return GVA_AvailableExternally;
7800
Rafael Espindola3ae00052013-05-13 00:12:11 +00007801 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007802 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007803 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007804 }
7805
7806 if (!FD->isInlined())
7807 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007808
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007809 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7810 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007811 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007812 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7813
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007814 // GNU or C99 inline semantics. Determine whether this symbol should be
7815 // externally visible.
7816 if (FD->isInlineDefinitionExternallyVisible())
7817 return External;
7818
7819 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007820 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007821 }
7822
David Majnemer54e3ba52014-04-02 23:17:29 +00007823 // Functions specified with extern and inline in -fms-compatibility mode
7824 // forcibly get emitted. While the body of the function cannot be later
7825 // replaced, the function definition cannot be discarded.
7826 if (FD->getMostRecentDecl()->isMSExternInline())
7827 return GVA_StrongODR;
7828
David Majnemer27d69db2014-04-28 22:17:59 +00007829 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007830}
7831
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007832static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7833 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7834 // dllexport/dllimport on inline functions.
7835 if (D->hasAttr<DLLImportAttr>()) {
7836 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7837 return GVA_AvailableExternally;
7838 } else if (D->hasAttr<DLLExportAttr>()) {
7839 if (L == GVA_DiscardableODR)
7840 return GVA_StrongODR;
7841 }
7842 return L;
7843}
7844
7845GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7846 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7847 FD);
7848}
7849
7850static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7851 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007852 if (!VD->isExternallyVisible())
7853 return GVA_Internal;
7854
David Majnemer27d69db2014-04-28 22:17:59 +00007855 if (VD->isStaticLocal()) {
7856 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7857 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7858 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7859 LexicalContext = LexicalContext->getLexicalParent();
7860
7861 // Let the static local variable inherit it's linkage from the nearest
7862 // enclosing function.
7863 if (LexicalContext)
7864 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007865 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007866
7867 // GVA_StrongODR function linkage is stronger than what we need,
7868 // downgrade to GVA_DiscardableODR.
7869 // This allows us to discard the variable if we never end up needing it.
7870 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7871 : StaticLocalLinkage;
7872 }
7873
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007874 // MSVC treats in-class initialized static data members as definitions.
7875 // By giving them non-strong linkage, out-of-line definitions won't
7876 // cause link errors.
7877 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7878 return GVA_DiscardableODR;
7879
Richard Smith8809a0c2013-09-27 20:14:12 +00007880 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007881 case TSK_Undeclared:
7882 case TSK_ExplicitSpecialization:
7883 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007884
Rafael Espindola3ae00052013-05-13 00:12:11 +00007885 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007886 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007887
David Majnemer27d69db2014-04-28 22:17:59 +00007888 case TSK_ExplicitInstantiationDeclaration:
7889 return GVA_AvailableExternally;
7890
Rafael Espindola3ae00052013-05-13 00:12:11 +00007891 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007892 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007893 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007894
7895 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007896}
7897
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007898GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7899 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7900 VD);
7901}
7902
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007903bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007904 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7905 if (!VD->isFileVarDecl())
7906 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00007907 // Global named register variables (GNU extension) are never emitted.
7908 if (VD->getStorageClass() == SC_Register)
7909 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007910 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7911 // We never need to emit an uninstantiated function template.
7912 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7913 return false;
7914 } else
7915 return false;
7916
7917 // If this is a member of a class template, we do not need to emit it.
7918 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007919 return false;
7920
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007921 // Weak references don't produce any output by themselves.
7922 if (D->hasAttr<WeakRefAttr>())
7923 return false;
7924
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007925 // Aliases and used decls are required.
7926 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7927 return true;
7928
7929 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7930 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007931 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007932 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007933
7934 // Constructors and destructors are required.
7935 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7936 return true;
7937
John McCall6bd2a892013-01-25 22:31:03 +00007938 // The key function for a class is required. This rule only comes
7939 // into play when inline functions can be key functions, though.
7940 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7941 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7942 const CXXRecordDecl *RD = MD->getParent();
7943 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7944 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7945 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7946 return true;
7947 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007948 }
7949 }
7950
7951 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7952
7953 // static, static inline, always_inline, and extern inline functions can
7954 // always be deferred. Normal inline functions can be deferred in C99/C++.
7955 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00007956 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
7957 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007958 return false;
7959 return true;
7960 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007961
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007962 const VarDecl *VD = cast<VarDecl>(D);
7963 assert(VD->isFileVarDecl() && "Expected file scoped var");
7964
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007965 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
7966 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007967 return false;
7968
Richard Smitha0e5e542012-11-12 21:38:00 +00007969 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007970 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00007971 if (L != GVA_Internal && L != GVA_AvailableExternally &&
7972 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00007973 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007974
Richard Smitha0e5e542012-11-12 21:38:00 +00007975 // Variables that have destruction with side-effects are required.
7976 if (VD->getType().isDestructedType())
7977 return true;
7978
7979 // Variables that have initialization with side-effects are required.
7980 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7981 return true;
7982
7983 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007984}
Charles Davis53c59df2010-08-16 03:33:14 +00007985
Reid Kleckner78af0702013-08-27 23:08:25 +00007986CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7987 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007988 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007989 if (IsCXXMethod)
7990 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007991
Reid Kleckner78af0702013-08-27 23:08:25 +00007992 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007993}
7994
Jay Foad39c79802011-01-12 09:06:06 +00007995bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007996 // Pass through to the C++ ABI object
7997 return ABI->isNearlyEmpty(RD);
7998}
7999
Reid Kleckner96f8f932014-02-05 17:27:08 +00008000VTableContextBase *ASTContext::getVTableContext() {
8001 if (!VTContext.get()) {
8002 if (Target->getCXXABI().isMicrosoft())
8003 VTContext.reset(new MicrosoftVTableContext(*this));
8004 else
8005 VTContext.reset(new ItaniumVTableContext(*this));
8006 }
8007 return VTContext.get();
8008}
8009
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008010MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008011 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008012 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008013 case TargetCXXABI::GenericItanium:
8014 case TargetCXXABI::GenericARM:
8015 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008016 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008017 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008018 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008019 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008020 }
David Blaikie83d382b2011-09-23 05:06:16 +00008021 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008022}
8023
Charles Davis53c59df2010-08-16 03:33:14 +00008024CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008025
8026size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008027 return ASTRecordLayouts.getMemorySize() +
8028 llvm::capacity_in_bytes(ObjCLayouts) +
8029 llvm::capacity_in_bytes(KeyFunctions) +
8030 llvm::capacity_in_bytes(ObjCImpls) +
8031 llvm::capacity_in_bytes(BlockVarCopyInits) +
8032 llvm::capacity_in_bytes(DeclAttrs) +
8033 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8034 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8035 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8036 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8037 llvm::capacity_in_bytes(OverriddenMethods) +
8038 llvm::capacity_in_bytes(Types) +
8039 llvm::capacity_in_bytes(VariableArrayTypes) +
8040 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008041}
Ted Kremenek540017e2011-10-06 05:00:56 +00008042
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008043/// getIntTypeForBitwidth -
8044/// sets integer QualTy according to specified details:
8045/// bitwidth, signed/unsigned.
8046/// Returns empty type if there is no appropriate target types.
8047QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8048 unsigned Signed) const {
8049 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8050 CanQualType QualTy = getFromTargetType(Ty);
8051 if (!QualTy && DestWidth == 128)
8052 return Signed ? Int128Ty : UnsignedInt128Ty;
8053 return QualTy;
8054}
8055
8056/// getRealTypeForBitwidth -
8057/// sets floating point QualTy according to specified bitwidth.
8058/// Returns empty type if there is no appropriate target types.
8059QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8060 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8061 switch (Ty) {
8062 case TargetInfo::Float:
8063 return FloatTy;
8064 case TargetInfo::Double:
8065 return DoubleTy;
8066 case TargetInfo::LongDouble:
8067 return LongDoubleTy;
8068 case TargetInfo::NoFloat:
8069 return QualType();
8070 }
8071
8072 llvm_unreachable("Unhandled TargetInfo::RealType value");
8073}
8074
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008075void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8076 if (Number > 1)
8077 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008078}
8079
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008080unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8081 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8082 MangleNumbers.find(ND);
8083 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008084}
8085
David Majnemer2206bf52014-03-05 08:57:59 +00008086void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8087 if (Number > 1)
8088 StaticLocalNumbers[VD] = Number;
8089}
8090
8091unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8092 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8093 StaticLocalNumbers.find(VD);
8094 return I != StaticLocalNumbers.end() ? I->second : 1;
8095}
8096
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008097MangleNumberingContext &
8098ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008099 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8100 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8101 if (!MCtx)
8102 MCtx = createMangleNumberingContext();
8103 return *MCtx;
8104}
8105
8106MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8107 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008108}
8109
Ted Kremenek540017e2011-10-06 05:00:56 +00008110void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8111 ParamIndices[D] = index;
8112}
8113
8114unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8115 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8116 assert(I != ParamIndices.end() &&
8117 "ParmIndices lacks entry set by ParmVarDecl");
8118 return I->second;
8119}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008120
Richard Smithe6c01442013-06-05 00:46:14 +00008121APValue *
8122ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8123 bool MayCreate) {
8124 assert(E && E->getStorageDuration() == SD_Static &&
8125 "don't need to cache the computed value for this temporary");
8126 if (MayCreate)
8127 return &MaterializedTemporaryValues[E];
8128
8129 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8130 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008131 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008132}
8133
Fariborz Jahanian615de762013-05-28 17:37:39 +00008134bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8135 const llvm::Triple &T = getTargetInfo().getTriple();
8136 if (!T.isOSDarwin())
8137 return false;
8138
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008139 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8140 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8141 return false;
8142
Fariborz Jahanian615de762013-05-28 17:37:39 +00008143 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8144 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8145 uint64_t Size = sizeChars.getQuantity();
8146 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8147 unsigned Align = alignChars.getQuantity();
8148 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8149 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8150}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008151
8152namespace {
8153
8154 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8155 /// parents as defined by the \c RecursiveASTVisitor.
8156 ///
8157 /// Note that the relationship described here is purely in terms of AST
8158 /// traversal - there are other relationships (for example declaration context)
8159 /// in the AST that are better modeled by special matchers.
8160 ///
8161 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8162 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8163
8164 public:
8165 /// \brief Builds and returns the translation unit's parent map.
8166 ///
8167 /// The caller takes ownership of the returned \c ParentMap.
8168 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8169 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8170 Visitor.TraverseDecl(&TU);
8171 return Visitor.Parents;
8172 }
8173
8174 private:
8175 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8176
8177 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8178 }
8179
8180 bool shouldVisitTemplateInstantiations() const {
8181 return true;
8182 }
8183 bool shouldVisitImplicitCode() const {
8184 return true;
8185 }
8186 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8187 // are not triggered during data recursion.
8188 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8189 return false;
8190 }
8191
8192 template <typename T>
8193 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008194 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008195 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008196 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008197 // FIXME: Currently we add the same parent multiple times, but only
8198 // when no memoization data is available for the type.
8199 // For example when we visit all subexpressions of template
8200 // instantiations; this is suboptimal, but benign: the only way to
8201 // visit those is with hasAncestor / hasParent, and those do not create
8202 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008203 // The plan is to enable DynTypedNode to be storable in a map or hash
8204 // map. The main problem there is to implement hash functions /
8205 // comparison operators for all types that DynTypedNode supports that
8206 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008207 auto &NodeOrVector = (*Parents)[Node];
8208 if (NodeOrVector.isNull()) {
8209 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008210 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008211 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8212 auto *Node =
8213 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8214 auto *Vector = new ASTContext::ParentVector(1, *Node);
8215 NodeOrVector = Vector;
8216 delete Node;
8217 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008218 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008219
8220 auto *Vector =
8221 NodeOrVector.template get<ASTContext::ParentVector *>();
8222 // Skip duplicates for types that have memoization data.
8223 // We must check that the type has memoization data before calling
8224 // std::find() because DynTypedNode::operator== can't compare all
8225 // types.
8226 bool Found = ParentStack.back().getMemoizationData() &&
8227 std::find(Vector->begin(), Vector->end(),
8228 ParentStack.back()) != Vector->end();
8229 if (!Found)
8230 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008231 }
8232 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008233 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8234 bool Result = (this ->* traverse) (Node);
8235 ParentStack.pop_back();
8236 return Result;
8237 }
8238
8239 bool TraverseDecl(Decl *DeclNode) {
8240 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8241 }
8242
8243 bool TraverseStmt(Stmt *StmtNode) {
8244 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8245 }
8246
8247 ASTContext::ParentMap *Parents;
8248 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8249
8250 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8251 };
8252
8253} // end namespace
8254
Benjamin Kramer07935292014-10-04 17:01:26 +00008255ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008256ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8257 assert(Node.getMemoizationData() &&
8258 "Invariant broken: only nodes that support memoization may be "
8259 "used in the parent map.");
8260 if (!AllParents) {
8261 // We always need to run over the whole translation unit, as
8262 // hasAncestor can escape any subtree.
8263 AllParents.reset(
8264 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8265 }
8266 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8267 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008268 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008269 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008270 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8271 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008272 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008273 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008274}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008275
8276bool
8277ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8278 const ObjCMethodDecl *MethodImpl) {
8279 // No point trying to match an unavailable/deprecated mothod.
8280 if (MethodDecl->hasAttr<UnavailableAttr>()
8281 || MethodDecl->hasAttr<DeprecatedAttr>())
8282 return false;
8283 if (MethodDecl->getObjCDeclQualifier() !=
8284 MethodImpl->getObjCDeclQualifier())
8285 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008286 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008287 return false;
8288
8289 if (MethodDecl->param_size() != MethodImpl->param_size())
8290 return false;
8291
8292 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8293 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8294 EF = MethodDecl->param_end();
8295 IM != EM && IF != EF; ++IM, ++IF) {
8296 const ParmVarDecl *DeclVar = (*IF);
8297 const ParmVarDecl *ImplVar = (*IM);
8298 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8299 return false;
8300 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8301 return false;
8302 }
8303 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8304
8305}
Richard Smith053f6c62014-05-16 23:01:30 +00008306
8307// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8308// doesn't include ASTContext.h
8309template
8310clang::LazyGenerationalUpdatePtr<
8311 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8312clang::LazyGenerationalUpdatePtr<
8313 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8314 const clang::ASTContext &Ctx, Decl *Value);