blob: 4be2436dc63a50d85439cddc899b232debb527a7 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
330} // unnamed namespace
331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
429 ThisDeclInfo);
430 return CFC;
431
432}
433
Richard Smithb39b9d52013-05-21 05:24:00 +0000434comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000437}
438
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000439comments::FullComment *ASTContext::getCommentForDecl(
440 const Decl *D,
441 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000442 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000443 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449
450 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 return CFC;
455 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000456 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 }
458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (!RC) {
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000464 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000470 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000476 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000478 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000479 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000480 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000484 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000485 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
497 }
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000500 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000501 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510 continue;
511
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000519 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000520 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000521 if (Ty.isNull())
522 continue;
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
525 continue;
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
528 }
529 }
530 }
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000532 }
533
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000542 ParsedComments[Canonical] = FC;
543 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000544}
545
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000546void
547ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000552
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
557 P != PEnd; ++P) {
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559 ID.AddInteger(0);
560 ID.AddBoolean(TTP->isParameterPack());
561 continue;
562 }
563
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000566 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000568 if (NTTP->isExpandedParameterPack()) {
569 ID.AddBoolean(true);
570 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000575 } else
576 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 continue;
578 }
579
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581 ID.AddInteger(2);
582 Profile(ID, TTP);
583 }
584}
585
586TemplateTemplateParmDecl *
587ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000588 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000592 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595 if (Canonical)
596 return Canonical->getParam();
597
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
604 P != PEnd; ++P) {
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000608 SourceLocation(),
609 SourceLocation(),
610 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000611 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625 }
626
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000628 SourceLocation(),
629 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000630 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000631 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 T,
633 TInfo,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
662 CanonParams.data(),
663 CanonParams.size(),
664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000687 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000688 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000689 return CreateMicrosoftCXXABI(*this);
690 }
David Blaikie8a40f702012-01-17 06:56:22 +0000691 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000692}
693
Douglas Gregore8bbc122011-09-02 00:18:52 +0000694static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000695 const LangOptions &LOpts) {
696 if (LOpts.FakeAddressSpaceMap) {
697 // The fake address space map must have a distinct entry for each
698 // language-specific address space.
699 static const unsigned FakeAddrSpaceMap[] = {
700 1, // opencl_global
701 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000702 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000703 4, // opencl_generic
704 5, // cuda_device
705 6, // cuda_constant
706 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000707 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 }
712}
713
David Tweed31d09b02013-09-13 12:04:22 +0000714static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
715 const LangOptions &LangOpts) {
716 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000717 case LangOptions::ASMM_Target:
718 return TI.useAddressSpaceMapMangling();
719 case LangOptions::ASMM_On:
720 return true;
721 case LangOptions::ASMM_Off:
722 return false;
723 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000724 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000725}
726
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000727ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000728 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000729 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000730 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
731 DependentTemplateSpecializationTypes(this_()),
732 SubstTemplateTemplateParmPacks(this_()),
733 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
734 UInt128Decl(nullptr), Float128StubDecl(nullptr),
735 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
736 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
739 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
740 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000741 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
742 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000743 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000744 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
745 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
746 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
747 Comments(SM), CommentsLoaded(false),
748 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000749 TUDecl = TranslationUnitDecl::Create(*this);
750}
751
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000752ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000753 ReleaseParentMapEntries();
754
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000755 // Release the DenseMaps associated with DeclContext objects.
756 // FIXME: Is this the ideal solution?
757 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000758
Manuel Klimeka7328992013-06-03 13:51:33 +0000759 // Call all of the deallocation functions on all of their targets.
760 for (DeallocationMap::const_iterator I = Deallocations.begin(),
761 E = Deallocations.end(); I != E; ++I)
762 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763 (I->first)((I->second)[J]);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
Reid Kleckner588c9372014-02-19 23:44:52 +0000786 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000787}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000788
Manuel Klimek95403e62014-05-21 13:28:59 +0000789void ASTContext::ReleaseParentMapEntries() {
790 if (!AllParents) return;
791 for (const auto &Entry : *AllParents) {
792 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
793 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
794 } else {
795 assert(Entry.second.is<ParentVector *>());
796 delete Entry.second.get<ParentVector *>();
797 }
798 }
799}
800
Douglas Gregor1a809332010-05-23 18:26:36 +0000801void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000802 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000803}
804
Mike Stump11289f42009-09-09 15:08:12 +0000805void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000806ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
807 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000808}
809
Chris Lattner4eb445d2007-01-26 01:27:23 +0000810void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000811 llvm::errs() << "\n*** AST Context Stats:\n";
812 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000813
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000815#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000816#define ABSTRACT_TYPE(Name, Parent)
817#include "clang/AST/TypeNodes.def"
818 0 // Extra
819 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000820
Chris Lattner4eb445d2007-01-26 01:27:23 +0000821 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
822 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000823 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000824 }
825
Douglas Gregora30d0462009-05-26 14:40:08 +0000826 unsigned Idx = 0;
827 unsigned TotalBytes = 0;
828#define TYPE(Name, Parent) \
829 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000830 llvm::errs() << " " << counts[Idx] << " " << #Name \
831 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 TotalBytes += counts[Idx] * sizeof(Name##Type); \
833 ++Idx;
834#define ABSTRACT_TYPE(Name, Parent)
835#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chandler Carruth3c147a72011-07-04 05:32:14 +0000837 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
838
Douglas Gregor7454c562010-07-02 20:37:36 +0000839 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000840 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
841 << NumImplicitDefaultConstructors
842 << " implicit default constructors created\n";
843 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
844 << NumImplicitCopyConstructors
845 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000846 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000847 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
848 << NumImplicitMoveConstructors
849 << " implicit move constructors created\n";
850 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
851 << NumImplicitCopyAssignmentOperators
852 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000853 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000854 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
855 << NumImplicitMoveAssignmentOperators
856 << " implicit move assignment operators created\n";
857 llvm::errs() << NumImplicitDestructorsDeclared << "/"
858 << NumImplicitDestructors
859 << " implicit destructors created\n";
860
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000861 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000862 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000863 ExternalSource->PrintStats();
864 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000865
Douglas Gregor5b11d492010-07-25 17:53:33 +0000866 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000867}
868
Richard Smithf19e1272015-03-07 00:04:49 +0000869ExternCContextDecl *ASTContext::getExternCContextDecl() const {
870 if (!ExternCContext)
871 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
872
873 return ExternCContext;
874}
875
Alp Toker2dea15b2013-12-17 01:22:38 +0000876RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
877 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000878 SourceLocation Loc;
879 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000880 if (getLangOpts().CPlusPlus)
881 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
882 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000883 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000884 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
885 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000886 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000887 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
888 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000889 return NewDecl;
890}
891
892TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
893 StringRef Name) const {
894 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
895 TypedefDecl *NewDecl = TypedefDecl::Create(
896 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
897 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
898 NewDecl->setImplicit();
899 return NewDecl;
900}
901
Douglas Gregor801c99d2011-08-12 06:49:56 +0000902TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000903 if (!Int128Decl)
904 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000905 return Int128Decl;
906}
907
908TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000909 if (!UInt128Decl)
910 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000911 return UInt128Decl;
912}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000913
Nico Webere1687c52013-06-20 21:44:55 +0000914TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000915 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000916 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000917 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000918
Nico Webere1687c52013-06-20 21:44:55 +0000919 return Float128StubDecl;
920}
921
John McCall48f2d582009-10-23 23:03:21 +0000922void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000923 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000924 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000925 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000926}
927
Douglas Gregore8bbc122011-09-02 00:18:52 +0000928void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
929 assert((!this->Target || this->Target == &Target) &&
930 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000931 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000932
Douglas Gregore8bbc122011-09-02 00:18:52 +0000933 this->Target = &Target;
934
935 ABI.reset(createCXXABI(Target));
936 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000937 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000938
Chris Lattner970e54e2006-11-12 00:37:36 +0000939 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000940 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner970e54e2006-11-12 00:37:36 +0000942 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000943 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000944 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000945 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000946 InitBuiltinType(CharTy, BuiltinType::Char_S);
947 else
948 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000949 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000950 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
951 InitBuiltinType(ShortTy, BuiltinType::Short);
952 InitBuiltinType(IntTy, BuiltinType::Int);
953 InitBuiltinType(LongTy, BuiltinType::Long);
954 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000955
Chris Lattner970e54e2006-11-12 00:37:36 +0000956 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000957 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
958 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
959 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
960 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
961 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000962
Chris Lattner970e54e2006-11-12 00:37:36 +0000963 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000964 InitBuiltinType(FloatTy, BuiltinType::Float);
965 InitBuiltinType(DoubleTy, BuiltinType::Double);
966 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000967
Chris Lattnerf122cef2009-04-30 02:43:43 +0000968 // GNU extension, 128-bit integers.
969 InitBuiltinType(Int128Ty, BuiltinType::Int128);
970 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
971
Hans Wennborg0d81e012013-05-10 10:08:40 +0000972 // C++ 3.9.1p5
973 if (TargetInfo::isTypeSigned(Target.getWCharType()))
974 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
975 else // -fshort-wchar makes wchar_t be unsigned.
976 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
977 if (LangOpts.CPlusPlus && LangOpts.WChar)
978 WideCharTy = WCharTy;
979 else {
980 // C99 (or C++ using -fno-wchar).
981 WideCharTy = getFromTargetType(Target.getWCharType());
982 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000983
James Molloy36365542012-05-04 10:55:22 +0000984 WIntTy = getFromTargetType(Target.getWIntType());
985
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000986 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
987 InitBuiltinType(Char16Ty, BuiltinType::Char16);
988 else // C99
989 Char16Ty = getFromTargetType(Target.getChar16Type());
990
991 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
992 InitBuiltinType(Char32Ty, BuiltinType::Char32);
993 else // C99
994 Char32Ty = getFromTargetType(Target.getChar32Type());
995
Douglas Gregor4619e432008-12-05 23:32:09 +0000996 // Placeholder type for type-dependent expressions whose type is
997 // completely unknown. No code should ever check a type against
998 // DependentTy and users should never see it; however, it is here to
999 // help diagnose failures to properly check for type-dependent
1000 // expressions.
1001 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001002
John McCall36e7fe32010-10-12 00:20:44 +00001003 // Placeholder type for functions.
1004 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1005
John McCall0009fcc2011-04-26 20:42:42 +00001006 // Placeholder type for bound members.
1007 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1008
John McCall526ab472011-10-25 17:37:35 +00001009 // Placeholder type for pseudo-objects.
1010 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1011
John McCall31996342011-04-07 08:22:57 +00001012 // "any" type; useful for debugger-like clients.
1013 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1014
John McCall8a6b59a2011-10-17 18:09:15 +00001015 // Placeholder type for unbridged ARC casts.
1016 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1017
Eli Friedman34866c72012-08-31 00:14:07 +00001018 // Placeholder type for builtin functions.
1019 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1020
Chris Lattner970e54e2006-11-12 00:37:36 +00001021 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001022 FloatComplexTy = getComplexType(FloatTy);
1023 DoubleComplexTy = getComplexType(DoubleTy);
1024 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001026 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001027 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1028 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001029 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001030
1031 if (LangOpts.OpenCL) {
1032 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1033 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1034 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1035 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1036 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1037 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001038
Guy Benyei61054192013-02-07 10:55:47 +00001039 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001040 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001041 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001042
1043 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001044 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1045 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001046
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001047 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001048
1049 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001050
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001051 // void * type
1052 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001053
1054 // nullptr type (C++0x 2.14.7)
1055 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001056
1057 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1058 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001059
1060 // Builtin type used to help define __builtin_va_list.
1061 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001062}
1063
David Blaikie9c902b52011-09-25 23:23:43 +00001064DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001065 return SourceMgr.getDiagnostics();
1066}
1067
Douglas Gregor561eceb2010-08-30 16:49:28 +00001068AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1069 AttrVec *&Result = DeclAttrs[D];
1070 if (!Result) {
1071 void *Mem = Allocate(sizeof(AttrVec));
1072 Result = new (Mem) AttrVec;
1073 }
1074
1075 return *Result;
1076}
1077
1078/// \brief Erase the attributes corresponding to the given declaration.
1079void ASTContext::eraseDeclAttrs(const Decl *D) {
1080 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1081 if (Pos != DeclAttrs.end()) {
1082 Pos->second->~AttrVec();
1083 DeclAttrs.erase(Pos);
1084 }
1085}
1086
Larisse Voufo39a1e502013-08-06 01:03:05 +00001087// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001088MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001089ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001090 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001091 return getTemplateOrSpecializationInfo(Var)
1092 .dyn_cast<MemberSpecializationInfo *>();
1093}
1094
1095ASTContext::TemplateOrSpecializationInfo
1096ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1097 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1098 TemplateOrInstantiation.find(Var);
1099 if (Pos == TemplateOrInstantiation.end())
1100 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001101
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001102 return Pos->second;
1103}
1104
Mike Stump11289f42009-09-09 15:08:12 +00001105void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001106ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001107 TemplateSpecializationKind TSK,
1108 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001109 assert(Inst->isStaticDataMember() && "Not a static data member");
1110 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001111 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1112 Tmpl, TSK, PointOfInstantiation));
1113}
1114
1115void
1116ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1117 TemplateOrSpecializationInfo TSI) {
1118 assert(!TemplateOrInstantiation[Inst] &&
1119 "Already noted what the variable was instantiated from");
1120 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001121}
1122
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001123FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1124 const FunctionDecl *FD){
1125 assert(FD && "Specialization is 0");
1126 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001127 = ClassScopeSpecializationPattern.find(FD);
1128 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001129 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001130
1131 return Pos->second;
1132}
1133
1134void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1135 FunctionDecl *Pattern) {
1136 assert(FD && "Specialization is 0");
1137 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001138 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001139}
1140
John McCalle61f2ba2009-11-18 02:36:19 +00001141NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001142ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001143 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001144 = InstantiatedFromUsingDecl.find(UUD);
1145 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001146 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001147
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001148 return Pos->second;
1149}
1150
1151void
John McCallb96ec562009-12-04 22:46:56 +00001152ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1153 assert((isa<UsingDecl>(Pattern) ||
1154 isa<UnresolvedUsingValueDecl>(Pattern) ||
1155 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1156 "pattern decl is not a using decl");
1157 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1158 InstantiatedFromUsingDecl[Inst] = Pattern;
1159}
1160
1161UsingShadowDecl *
1162ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1163 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1164 = InstantiatedFromUsingShadowDecl.find(Inst);
1165 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001166 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001167
1168 return Pos->second;
1169}
1170
1171void
1172ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1173 UsingShadowDecl *Pattern) {
1174 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1175 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001176}
1177
Anders Carlsson5da84842009-09-01 04:26:58 +00001178FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1179 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1180 = InstantiatedFromUnnamedFieldDecl.find(Field);
1181 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001182 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001183
Anders Carlsson5da84842009-09-01 04:26:58 +00001184 return Pos->second;
1185}
1186
1187void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1188 FieldDecl *Tmpl) {
1189 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1190 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1191 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1192 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001193
Anders Carlsson5da84842009-09-01 04:26:58 +00001194 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1195}
1196
Douglas Gregor832940b2010-03-02 23:58:15 +00001197ASTContext::overridden_cxx_method_iterator
1198ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001200 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001201 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001202 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001203
1204 return Pos->second.begin();
1205}
1206
1207ASTContext::overridden_cxx_method_iterator
1208ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1209 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001210 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001211 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001212 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001213
1214 return Pos->second.end();
1215}
1216
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001217unsigned
1218ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1219 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001220 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001221 if (Pos == OverriddenMethods.end())
1222 return 0;
1223
1224 return Pos->second.size();
1225}
1226
Douglas Gregor832940b2010-03-02 23:58:15 +00001227void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1228 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001229 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001230 OverriddenMethods[Method].push_back(Overridden);
1231}
1232
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001233void ASTContext::getOverriddenMethods(
1234 const NamedDecl *D,
1235 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001236 assert(D);
1237
1238 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001239 Overridden.append(overridden_methods_begin(CXXMethod),
1240 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001241 return;
1242 }
1243
1244 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1245 if (!Method)
1246 return;
1247
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001248 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1249 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001250 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001251}
1252
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001253void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1254 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1255 assert(!Import->isFromASTFile() && "Non-local import declaration");
1256 if (!FirstLocalImport) {
1257 FirstLocalImport = Import;
1258 LastLocalImport = Import;
1259 return;
1260 }
1261
1262 LastLocalImport->NextLocalImport = Import;
1263 LastLocalImport = Import;
1264}
1265
Chris Lattner53cfe802007-07-18 17:52:12 +00001266//===----------------------------------------------------------------------===//
1267// Type Sizing and Analysis
1268//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001269
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001270/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1271/// scalar floating point type.
1272const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001273 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001274 assert(BT && "Not a floating point type!");
1275 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001276 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001277 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001278 case BuiltinType::Float: return Target->getFloatFormat();
1279 case BuiltinType::Double: return Target->getDoubleFormat();
1280 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001281 }
1282}
1283
Rafael Espindola71eccb32013-08-08 19:53:46 +00001284CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001285 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001286
John McCall94268702010-10-08 18:24:19 +00001287 bool UseAlignAttrOnly = false;
1288 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1289 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001290
John McCall94268702010-10-08 18:24:19 +00001291 // __attribute__((aligned)) can increase or decrease alignment
1292 // *except* on a struct or struct member, where it only increases
1293 // alignment unless 'packed' is also specified.
1294 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001295 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001296 // ignore that possibility; Sema should diagnose it.
1297 if (isa<FieldDecl>(D)) {
1298 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1299 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1300 } else {
1301 UseAlignAttrOnly = true;
1302 }
1303 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001304 else if (isa<FieldDecl>(D))
1305 UseAlignAttrOnly =
1306 D->hasAttr<PackedAttr>() ||
1307 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001308
John McCall4e819612011-01-20 07:57:12 +00001309 // If we're using the align attribute only, just ignore everything
1310 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001311 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001312 // do nothing
1313
John McCall94268702010-10-08 18:24:19 +00001314 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001315 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001316 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001317 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001318 T = RT->getPointeeType();
1319 else
1320 T = getPointerType(RT->getPointeeType());
1321 }
Richard Smithf6d70302014-06-10 23:34:28 +00001322 QualType BaseT = getBaseElementType(T);
1323 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001324 // Adjust alignments of declarations with array type by the
1325 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001326 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001327 unsigned MinWidth = Target->getLargeArrayMinWidth();
1328 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001329 if (isa<VariableArrayType>(arrayType))
1330 Align = std::max(Align, Target->getLargeArrayAlign());
1331 else if (isa<ConstantArrayType>(arrayType) &&
1332 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1333 Align = std::max(Align, Target->getLargeArrayAlign());
1334 }
John McCall33ddac02011-01-19 10:06:00 +00001335 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001336 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001337 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1338 if (VD->hasGlobalStorage())
1339 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1340 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001341 }
John McCall4e819612011-01-20 07:57:12 +00001342
1343 // Fields can be subject to extra alignment constraints, like if
1344 // the field is packed, the struct is packed, or the struct has a
1345 // a max-field-alignment constraint (#pragma pack). So calculate
1346 // the actual alignment of the field within the struct, and then
1347 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001348 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1349 const RecordDecl *Parent = Field->getParent();
1350 // We can only produce a sensible answer if the record is valid.
1351 if (!Parent->isInvalidDecl()) {
1352 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001353
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001354 // Start with the record's overall alignment.
1355 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001356
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001357 // Use the GCD of that and the offset within the record.
1358 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1359 if (Offset > 0) {
1360 // Alignment is always a power of 2, so the GCD will be a power of 2,
1361 // which means we get to do this crazy thing instead of Euclid's.
1362 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1363 if (LowBitOfOffset < FieldAlign)
1364 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1365 }
1366
1367 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001368 }
Charles Davis3fc51072010-02-23 04:52:00 +00001369 }
Chris Lattner68061312009-01-24 21:53:27 +00001370 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001371
Ken Dyckcc56c542011-01-15 18:38:59 +00001372 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001373}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001374
John McCallf1249922012-08-21 04:10:00 +00001375// getTypeInfoDataSizeInChars - Return the size of a type, in
1376// chars. If the type is a record, its data size is returned. This is
1377// the size of the memcpy that's performed when assigning this type
1378// using a trivial copy/move assignment operator.
1379std::pair<CharUnits, CharUnits>
1380ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1381 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1382
1383 // In C++, objects can sometimes be allocated into the tail padding
1384 // of a base-class subobject. We decide whether that's possible
1385 // during class layout, so here we can just trust the layout results.
1386 if (getLangOpts().CPlusPlus) {
1387 if (const RecordType *RT = T->getAs<RecordType>()) {
1388 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1389 sizeAndAlign.first = layout.getDataSize();
1390 }
1391 }
1392
1393 return sizeAndAlign;
1394}
1395
Richard Trieu04d2d942013-05-14 21:59:17 +00001396/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1397/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1398std::pair<CharUnits, CharUnits>
1399static getConstantArrayInfoInChars(const ASTContext &Context,
1400 const ConstantArrayType *CAT) {
1401 std::pair<CharUnits, CharUnits> EltInfo =
1402 Context.getTypeInfoInChars(CAT->getElementType());
1403 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001404 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1405 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001406 "Overflow in array type char size evaluation");
1407 uint64_t Width = EltInfo.first.getQuantity() * Size;
1408 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001409 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1410 Context.getTargetInfo().getPointerWidth(0) == 64)
1411 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001412 return std::make_pair(CharUnits::fromQuantity(Width),
1413 CharUnits::fromQuantity(Align));
1414}
1415
John McCall87fe5d52010-05-20 01:18:31 +00001416std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001417ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001418 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1419 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001420 TypeInfo Info = getTypeInfo(T);
1421 return std::make_pair(toCharUnitsFromBits(Info.Width),
1422 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001423}
1424
1425std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001426ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001427 return getTypeInfoInChars(T.getTypePtr());
1428}
1429
David Majnemer34b57492014-07-30 01:30:47 +00001430bool ASTContext::isAlignmentRequired(const Type *T) const {
1431 return getTypeInfo(T).AlignIsRequired;
1432}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001433
David Majnemer34b57492014-07-30 01:30:47 +00001434bool ASTContext::isAlignmentRequired(QualType T) const {
1435 return isAlignmentRequired(T.getTypePtr());
1436}
1437
1438TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001439 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1440 if (I != MemoizedTypeInfo.end())
1441 return I->second;
1442
1443 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1444 TypeInfo TI = getTypeInfoImpl(T);
1445 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001446 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001447}
1448
1449/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1450/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001451///
1452/// FIXME: Pointers into different addr spaces could have different sizes and
1453/// alignment requirements: getPointerInfo should take an AddrSpace, this
1454/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001455TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1456 uint64_t Width = 0;
1457 unsigned Align = 8;
1458 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001459 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001460#define TYPE(Class, Base)
1461#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001462#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001463#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001464#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1465 case Type::Class: \
1466 assert(!T->isDependentType() && "should not see dependent types here"); \
1467 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001468#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001469 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001470
Chris Lattner355332d2007-07-13 22:27:08 +00001471 case Type::FunctionNoProto:
1472 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001473 // GCC extension: alignof(function) = 32 bits
1474 Width = 0;
1475 Align = 32;
1476 break;
1477
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001478 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001479 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001480 Width = 0;
1481 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1482 break;
1483
Steve Naroff5c131802007-08-30 01:06:46 +00001484 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001485 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001486
David Majnemer34b57492014-07-30 01:30:47 +00001487 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001488 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001489 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001490 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001491 Width = EltInfo.Width * Size;
1492 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001493 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1494 getTargetInfo().getPointerWidth(0) == 64)
1495 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001496 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001497 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001498 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001499 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001500 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001501 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1502 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001503 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001504 // If the alignment is not a power of 2, round up to the next power of 2.
1505 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001506 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001507 Align = llvm::NextPowerOf2(Align);
1508 Width = llvm::RoundUpToAlignment(Width, Align);
1509 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001510 // Adjust the alignment based on the target max.
1511 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1512 if (TargetVectorAlign && TargetVectorAlign < Align)
1513 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001514 break;
1515 }
Chris Lattner647fb222007-07-18 18:26:58 +00001516
Chris Lattner7570e9c2008-03-08 08:52:55 +00001517 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001518 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001519 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001520 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001521 // GCC extension: alignof(void) = 8 bits.
1522 Width = 0;
1523 Align = 8;
1524 break;
1525
Chris Lattner6a4f7452007-12-19 19:23:28 +00001526 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001527 Width = Target->getBoolWidth();
1528 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001530 case BuiltinType::Char_S:
1531 case BuiltinType::Char_U:
1532 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001533 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001534 Width = Target->getCharWidth();
1535 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001536 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001537 case BuiltinType::WChar_S:
1538 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001539 Width = Target->getWCharWidth();
1540 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001541 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001542 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001543 Width = Target->getChar16Width();
1544 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001545 break;
1546 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001547 Width = Target->getChar32Width();
1548 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001549 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001550 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getShortWidth();
1553 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001555 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001556 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001557 Width = Target->getIntWidth();
1558 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001559 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001560 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001561 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001562 Width = Target->getLongWidth();
1563 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001564 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001565 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001566 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001567 Width = Target->getLongLongWidth();
1568 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001569 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001570 case BuiltinType::Int128:
1571 case BuiltinType::UInt128:
1572 Width = 128;
1573 Align = 128; // int128_t is 128-bit aligned on all targets.
1574 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001575 case BuiltinType::Half:
1576 Width = Target->getHalfWidth();
1577 Align = Target->getHalfAlign();
1578 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001579 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001580 Width = Target->getFloatWidth();
1581 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001582 break;
1583 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001584 Width = Target->getDoubleWidth();
1585 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001586 break;
1587 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001588 Width = Target->getLongDoubleWidth();
1589 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001590 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001591 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1593 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001594 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001595 case BuiltinType::ObjCId:
1596 case BuiltinType::ObjCClass:
1597 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001598 Width = Target->getPointerWidth(0);
1599 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001600 break;
Guy Benyei61054192013-02-07 10:55:47 +00001601 case BuiltinType::OCLSampler:
1602 // Samplers are modeled as integers.
1603 Width = Target->getIntWidth();
1604 Align = Target->getIntAlign();
1605 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001606 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001607 case BuiltinType::OCLImage1d:
1608 case BuiltinType::OCLImage1dArray:
1609 case BuiltinType::OCLImage1dBuffer:
1610 case BuiltinType::OCLImage2d:
1611 case BuiltinType::OCLImage2dArray:
1612 case BuiltinType::OCLImage3d:
1613 // Currently these types are pointers to opaque types.
1614 Width = Target->getPointerWidth(0);
1615 Align = Target->getPointerAlign(0);
1616 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001617 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001618 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001619 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001620 Width = Target->getPointerWidth(0);
1621 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001622 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001623 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001624 unsigned AS = getTargetAddressSpace(
1625 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001626 Width = Target->getPointerWidth(AS);
1627 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001628 break;
1629 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001630 case Type::LValueReference:
1631 case Type::RValueReference: {
1632 // alignof and sizeof should never enter this code path here, so we go
1633 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001634 unsigned AS = getTargetAddressSpace(
1635 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001636 Width = Target->getPointerWidth(AS);
1637 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001638 break;
1639 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001640 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001641 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001642 Width = Target->getPointerWidth(AS);
1643 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001644 break;
1645 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001646 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001647 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001648 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001649 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001650 }
Chris Lattner647fb222007-07-18 18:26:58 +00001651 case Type::Complex: {
1652 // Complex types have the same alignment as their elements, but twice the
1653 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001654 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1655 Width = EltInfo.Width * 2;
1656 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001657 break;
1658 }
John McCall8b07ec22010-05-15 11:32:37 +00001659 case Type::ObjCObject:
1660 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001661 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001662 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001663 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001664 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001665 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001666 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001667 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001668 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001669 break;
1670 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001671 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001672 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001673 const TagType *TT = cast<TagType>(T);
1674
1675 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001676 Width = 8;
1677 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001678 break;
1679 }
Mike Stump11289f42009-09-09 15:08:12 +00001680
David Majnemer475b25e2015-01-21 10:54:38 +00001681 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1682 const EnumDecl *ED = ET->getDecl();
1683 TypeInfo Info =
1684 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1685 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1686 Info.Align = AttrAlign;
1687 Info.AlignIsRequired = true;
1688 }
1689 return Info;
1690 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001691
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001692 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001693 const RecordDecl *RD = RT->getDecl();
1694 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001695 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001696 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001697 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001698 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001699 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001700
Chris Lattner63d2b362009-10-22 05:17:15 +00001701 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001702 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1703 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001704
Richard Smith30482bc2011-02-20 03:19:35 +00001705 case Type::Auto: {
1706 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001707 assert(!A->getDeducedType().isNull() &&
1708 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001709 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001710 }
1711
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001712 case Type::Paren:
1713 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1714
Douglas Gregoref462e62009-04-30 17:32:17 +00001715 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001716 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001717 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001718 // If the typedef has an aligned attribute on it, it overrides any computed
1719 // alignment we have. This violates the GCC documentation (which says that
1720 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001721 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001722 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001723 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001724 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001725 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001726 AlignIsRequired = Info.AlignIsRequired;
1727 }
David Majnemer34b57492014-07-30 01:30:47 +00001728 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001729 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001730 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001731
Abramo Bagnara6150c882010-05-11 21:36:43 +00001732 case Type::Elaborated:
1733 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001734
John McCall81904512011-01-06 01:58:22 +00001735 case Type::Attributed:
1736 return getTypeInfo(
1737 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1738
Eli Friedman0dfb8892011-10-06 23:00:33 +00001739 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001740 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001741 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1742 Width = Info.Width;
1743 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001744
1745 // If the size of the type doesn't exceed the platform's max
1746 // atomic promotion width, make the size and alignment more
1747 // favorable to atomic operations:
1748 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1749 // Round the size up to a power of 2.
1750 if (!llvm::isPowerOf2_64(Width))
1751 Width = llvm::NextPowerOf2(Width);
1752
1753 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001754 Align = static_cast<unsigned>(Width);
1755 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001756 }
1757
Douglas Gregoref462e62009-04-30 17:32:17 +00001758 }
Mike Stump11289f42009-09-09 15:08:12 +00001759
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001760 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001761 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001762}
1763
Ken Dyckcc56c542011-01-15 18:38:59 +00001764/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1765CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1766 return CharUnits::fromQuantity(BitSize / getCharWidth());
1767}
1768
Ken Dyckb0fcc592011-02-11 01:54:29 +00001769/// toBits - Convert a size in characters to a size in characters.
1770int64_t ASTContext::toBits(CharUnits CharSize) const {
1771 return CharSize.getQuantity() * getCharWidth();
1772}
1773
Ken Dyck8c89d592009-12-22 14:23:30 +00001774/// getTypeSizeInChars - Return the size of the specified type, in characters.
1775/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001776CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001777 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001778}
Jay Foad39c79802011-01-12 09:06:06 +00001779CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001780 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001781}
1782
Ken Dycka6046ab2010-01-26 17:25:18 +00001783/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001784/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001785CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001786 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001787}
Jay Foad39c79802011-01-12 09:06:06 +00001788CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001789 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001790}
1791
Chris Lattnera3402cd2009-01-27 18:08:34 +00001792/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1793/// type for the current target in bits. This can be different than the ABI
1794/// alignment in cases where it is beneficial for performance to overalign
1795/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001796unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001797 TypeInfo TI = getTypeInfo(T);
1798 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001799
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001800 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1801 return ABIAlign; // Never overalign on XCore.
1802
Eli Friedman7ab09572009-05-25 21:27:19 +00001803 // Double and long long should be naturally aligned if possible.
Richard Smithd7e1fe42014-06-10 23:43:44 +00001804 T = T->getBaseElementTypeUnsafe();
David Majnemer1d4db8f2014-02-24 23:43:27 +00001805 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001806 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001807 if (const EnumType *ET = T->getAs<EnumType>())
1808 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001809 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001810 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1811 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001812 // Don't increase the alignment if an alignment attribute was specified on a
1813 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001814 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001815 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001816
Chris Lattnera3402cd2009-01-27 18:08:34 +00001817 return ABIAlign;
1818}
1819
Ulrich Weigandfa806422013-05-06 16:23:57 +00001820/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1821/// to a global variable of the specified type.
1822unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1823 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1824}
1825
1826/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1827/// should be given to a global variable of the specified type.
1828CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1829 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1830}
1831
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001832/// DeepCollectObjCIvars -
1833/// This routine first collects all declared, but not synthesized, ivars in
1834/// super class and then collects all ivars, including those synthesized for
1835/// current class. This routine is used for implementation of current class
1836/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001837///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001838void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1839 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001840 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001841 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1842 DeepCollectObjCIvars(SuperClass, false, Ivars);
1843 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001844 for (const auto *I : OI->ivars())
1845 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001846 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001847 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001848 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001849 Iv= Iv->getNextIvar())
1850 Ivars.push_back(Iv);
1851 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001852}
1853
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001854/// CollectInheritedProtocols - Collect all protocols in current class and
1855/// those inherited by it.
1856void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001857 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001858 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001859 // We can use protocol_iterator here instead of
1860 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001861 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001862 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001863 for (auto *P : Proto->protocols()) {
1864 Protocols.insert(P->getCanonicalDecl());
1865 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001866 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001867 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001868
1869 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001870 for (const auto *Cat : OI->visible_categories())
1871 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001872
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001873 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1874 while (SD) {
1875 CollectInheritedProtocols(SD, Protocols);
1876 SD = SD->getSuperClass();
1877 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001878 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001879 for (auto *Proto : OC->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001880 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001881 for (const auto *P : Proto->protocols())
1882 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001883 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001884 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001885 for (auto *Proto : OP->protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001886 Protocols.insert(Proto->getCanonicalDecl());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001887 for (const auto *P : Proto->protocols())
1888 CollectInheritedProtocols(P, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001889 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001890 }
1891}
1892
Jay Foad39c79802011-01-12 09:06:06 +00001893unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001894 unsigned count = 0;
1895 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001896 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001897 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001898
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001899 // Count ivar defined in this class's implementation. This
1900 // includes synthesized ivars.
1901 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001902 count += ImplDecl->ivar_size();
1903
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001904 return count;
1905}
1906
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001907bool ASTContext::isSentinelNullExpr(const Expr *E) {
1908 if (!E)
1909 return false;
1910
1911 // nullptr_t is always treated as null.
1912 if (E->getType()->isNullPtrType()) return true;
1913
1914 if (E->getType()->isAnyPointerType() &&
1915 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1916 Expr::NPC_ValueDependentIsNull))
1917 return true;
1918
1919 // Unfortunately, __null has type 'int'.
1920 if (isa<GNUNullExpr>(E)) return true;
1921
1922 return false;
1923}
1924
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001925/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1926ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1927 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1928 I = ObjCImpls.find(D);
1929 if (I != ObjCImpls.end())
1930 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001931 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001932}
1933/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1934ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1935 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1936 I = ObjCImpls.find(D);
1937 if (I != ObjCImpls.end())
1938 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00001939 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001940}
1941
1942/// \brief Set the implementation of ObjCInterfaceDecl.
1943void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1944 ObjCImplementationDecl *ImplD) {
1945 assert(IFaceD && ImplD && "Passed null params");
1946 ObjCImpls[IFaceD] = ImplD;
1947}
1948/// \brief Set the implementation of ObjCCategoryDecl.
1949void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1950 ObjCCategoryImplDecl *ImplD) {
1951 assert(CatD && ImplD && "Passed null params");
1952 ObjCImpls[CatD] = ImplD;
1953}
1954
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001955const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1956 const NamedDecl *ND) const {
1957 if (const ObjCInterfaceDecl *ID =
1958 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001959 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001960 if (const ObjCCategoryDecl *CD =
1961 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001962 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001963 if (const ObjCImplDecl *IMD =
1964 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001965 return IMD->getClassInterface();
1966
Craig Topper36250ad2014-05-12 05:36:57 +00001967 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001968}
1969
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001970/// \brief Get the copy initialization expression of VarDecl,or NULL if
1971/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001972Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001973 assert(VD && "Passed null params");
1974 assert(VD->hasAttr<BlocksAttr>() &&
1975 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001976 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001977 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00001978 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001979}
1980
1981/// \brief Set the copy inialization expression of a block var decl.
1982void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1983 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001984 assert(VD->hasAttr<BlocksAttr>() &&
1985 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001986 BlockVarCopyInits[VD] = Init;
1987}
1988
John McCallbcd03502009-12-07 02:54:59 +00001989TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001990 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001991 if (!DataSize)
1992 DataSize = TypeLoc::getFullDataSizeForType(T);
1993 else
1994 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001995 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001996
John McCallbcd03502009-12-07 02:54:59 +00001997 TypeSourceInfo *TInfo =
1998 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1999 new (TInfo) TypeSourceInfo(T);
2000 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002001}
2002
John McCallbcd03502009-12-07 02:54:59 +00002003TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002004 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002005 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002006 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002007 return DI;
2008}
2009
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002010const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002011ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002012 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002013}
2014
2015const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002016ASTContext::getASTObjCImplementationLayout(
2017 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002018 return getObjCLayout(D->getClassInterface(), D);
2019}
2020
Chris Lattner983a8bb2007-07-13 22:13:22 +00002021//===----------------------------------------------------------------------===//
2022// Type creation/memoization methods
2023//===----------------------------------------------------------------------===//
2024
Jay Foad39c79802011-01-12 09:06:06 +00002025QualType
John McCall33ddac02011-01-19 10:06:00 +00002026ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2027 unsigned fastQuals = quals.getFastQualifiers();
2028 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002029
2030 // Check if we've already instantiated this type.
2031 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002032 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002033 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002034 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2035 assert(eq->getQualifiers() == quals);
2036 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002037 }
2038
John McCall33ddac02011-01-19 10:06:00 +00002039 // If the base type is not canonical, make the appropriate canonical type.
2040 QualType canon;
2041 if (!baseType->isCanonicalUnqualified()) {
2042 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002043 canonSplit.Quals.addConsistentQualifiers(quals);
2044 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002045
2046 // Re-find the insert position.
2047 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2048 }
2049
2050 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2051 ExtQualNodes.InsertNode(eq, insertPos);
2052 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002053}
2054
Jay Foad39c79802011-01-12 09:06:06 +00002055QualType
2056ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002057 QualType CanT = getCanonicalType(T);
2058 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002059 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002060
John McCall8ccfcb52009-09-24 19:53:00 +00002061 // If we are composing extended qualifiers together, merge together
2062 // into one ExtQuals node.
2063 QualifierCollector Quals;
2064 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002065
John McCall8ccfcb52009-09-24 19:53:00 +00002066 // If this type already has an address space specified, it cannot get
2067 // another one.
2068 assert(!Quals.hasAddressSpace() &&
2069 "Type cannot be in multiple addr spaces!");
2070 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002071
John McCall8ccfcb52009-09-24 19:53:00 +00002072 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002073}
2074
Chris Lattnerd60183d2009-02-18 22:53:11 +00002075QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002076 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002077 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002078 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002079 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002080
John McCall53fa7142010-12-24 02:08:15 +00002081 if (const PointerType *ptr = T->getAs<PointerType>()) {
2082 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002083 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002084 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2085 return getPointerType(ResultType);
2086 }
2087 }
Mike Stump11289f42009-09-09 15:08:12 +00002088
John McCall8ccfcb52009-09-24 19:53:00 +00002089 // If we are composing extended qualifiers together, merge together
2090 // into one ExtQuals node.
2091 QualifierCollector Quals;
2092 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002093
John McCall8ccfcb52009-09-24 19:53:00 +00002094 // If this type already has an ObjCGC specified, it cannot get
2095 // another one.
2096 assert(!Quals.hasObjCGCAttr() &&
2097 "Type cannot have multiple ObjCGCs!");
2098 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002099
John McCall8ccfcb52009-09-24 19:53:00 +00002100 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002101}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002102
John McCall4f5019e2010-12-19 02:44:49 +00002103const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2104 FunctionType::ExtInfo Info) {
2105 if (T->getExtInfo() == Info)
2106 return T;
2107
2108 QualType Result;
2109 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002110 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002111 } else {
2112 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2113 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2114 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002115 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002116 }
2117
2118 return cast<FunctionType>(Result.getTypePtr());
2119}
2120
Richard Smith2a7d4812013-05-04 07:00:32 +00002121void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2122 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002123 FD = FD->getMostRecentDecl();
2124 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002125 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2126 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002127 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002128 if (FunctionDecl *Next = FD->getPreviousDecl())
2129 FD = Next;
2130 else
2131 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002132 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002133 if (ASTMutationListener *L = getASTMutationListener())
2134 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002135}
2136
Richard Smith0b3a4622014-11-13 20:01:57 +00002137/// Get a function type and produce the equivalent function type with the
2138/// specified exception specification. Type sugar that can be present on a
2139/// declaration of a function with an exception specification is permitted
2140/// and preserved. Other type sugar (for instance, typedefs) is not.
2141static QualType getFunctionTypeWithExceptionSpec(
2142 ASTContext &Context, QualType Orig,
2143 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2144 // Might have some parens.
2145 if (auto *PT = dyn_cast<ParenType>(Orig))
2146 return Context.getParenType(
2147 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2148
2149 // Might have a calling-convention attribute.
2150 if (auto *AT = dyn_cast<AttributedType>(Orig))
2151 return Context.getAttributedType(
2152 AT->getAttrKind(),
2153 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2154 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2155 ESI));
2156
2157 // Anything else must be a function type. Rebuild it with the new exception
2158 // specification.
2159 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2160 return Context.getFunctionType(
2161 Proto->getReturnType(), Proto->getParamTypes(),
2162 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2163}
2164
2165void ASTContext::adjustExceptionSpec(
2166 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2167 bool AsWritten) {
2168 // Update the type.
2169 QualType Updated =
2170 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2171 FD->setType(Updated);
2172
2173 if (!AsWritten)
2174 return;
2175
2176 // Update the type in the type source information too.
2177 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2178 // If the type and the type-as-written differ, we may need to update
2179 // the type-as-written too.
2180 if (TSInfo->getType() != FD->getType())
2181 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2182
2183 // FIXME: When we get proper type location information for exceptions,
2184 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2185 // up the TypeSourceInfo;
2186 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2187 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2188 "TypeLoc size mismatch from updating exception specification");
2189 TSInfo->overrideType(Updated);
2190 }
2191}
2192
Chris Lattnerc6395932007-06-22 20:56:16 +00002193/// getComplexType - Return the uniqued reference to the type for a complex
2194/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002195QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002196 // Unique pointers, to guarantee there is only one pointer of a particular
2197 // structure.
2198 llvm::FoldingSetNodeID ID;
2199 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002200
Craig Topper36250ad2014-05-12 05:36:57 +00002201 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002202 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2203 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002204
Chris Lattnerc6395932007-06-22 20:56:16 +00002205 // If the pointee type isn't canonical, this won't be a canonical type either,
2206 // so fill in the canonical type field.
2207 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002208 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002209 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnerc6395932007-06-22 20:56:16 +00002211 // Get the new insert position for the node we care about.
2212 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002213 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002214 }
John McCall90d1c2d2009-09-24 23:30:46 +00002215 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002216 Types.push_back(New);
2217 ComplexTypes.InsertNode(New, InsertPos);
2218 return QualType(New, 0);
2219}
2220
Chris Lattner970e54e2006-11-12 00:37:36 +00002221/// getPointerType - Return the uniqued reference to the type for a pointer to
2222/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002223QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002224 // Unique pointers, to guarantee there is only one pointer of a particular
2225 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002226 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002227 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002228
Craig Topper36250ad2014-05-12 05:36:57 +00002229 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002230 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002231 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002232
Chris Lattner7ccecb92006-11-12 08:50:50 +00002233 // If the pointee type isn't canonical, this won't be a canonical type either,
2234 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002235 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002236 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002237 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002238
Bob Wilsonc8541f22013-03-15 17:12:43 +00002239 // Get the new insert position for the node we care about.
2240 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002241 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002242 }
John McCall90d1c2d2009-09-24 23:30:46 +00002243 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002244 Types.push_back(New);
2245 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002246 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002247}
2248
Reid Kleckner0503a872013-12-05 01:23:43 +00002249QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2250 llvm::FoldingSetNodeID ID;
2251 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002252 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002253 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2254 if (AT)
2255 return QualType(AT, 0);
2256
2257 QualType Canonical = getCanonicalType(New);
2258
2259 // Get the new insert position for the node we care about.
2260 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002261 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002262
2263 AT = new (*this, TypeAlignment)
2264 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2265 Types.push_back(AT);
2266 AdjustedTypes.InsertNode(AT, InsertPos);
2267 return QualType(AT, 0);
2268}
2269
Reid Kleckner8a365022013-06-24 17:51:48 +00002270QualType ASTContext::getDecayedType(QualType T) const {
2271 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2272
Reid Kleckner8a365022013-06-24 17:51:48 +00002273 QualType Decayed;
2274
2275 // C99 6.7.5.3p7:
2276 // A declaration of a parameter as "array of type" shall be
2277 // adjusted to "qualified pointer to type", where the type
2278 // qualifiers (if any) are those specified within the [ and ] of
2279 // the array type derivation.
2280 if (T->isArrayType())
2281 Decayed = getArrayDecayedType(T);
2282
2283 // C99 6.7.5.3p8:
2284 // A declaration of a parameter as "function returning type"
2285 // shall be adjusted to "pointer to function returning type", as
2286 // in 6.3.2.1.
2287 if (T->isFunctionType())
2288 Decayed = getPointerType(T);
2289
Reid Kleckner0503a872013-12-05 01:23:43 +00002290 llvm::FoldingSetNodeID ID;
2291 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002292 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002293 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2294 if (AT)
2295 return QualType(AT, 0);
2296
Reid Kleckner8a365022013-06-24 17:51:48 +00002297 QualType Canonical = getCanonicalType(Decayed);
2298
2299 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002300 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002301 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002302
Reid Kleckner0503a872013-12-05 01:23:43 +00002303 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2304 Types.push_back(AT);
2305 AdjustedTypes.InsertNode(AT, InsertPos);
2306 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002307}
2308
Mike Stump11289f42009-09-09 15:08:12 +00002309/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002310/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002311QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002312 assert(T->isFunctionType() && "block of function types only");
2313 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002314 // structure.
2315 llvm::FoldingSetNodeID ID;
2316 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002317
Craig Topper36250ad2014-05-12 05:36:57 +00002318 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002319 if (BlockPointerType *PT =
2320 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2321 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002322
2323 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002324 // type either so fill in the canonical type field.
2325 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002326 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002327 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002328
Steve Naroffec33ed92008-08-27 16:04:49 +00002329 // Get the new insert position for the node we care about.
2330 BlockPointerType *NewIP =
2331 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002332 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002333 }
John McCall90d1c2d2009-09-24 23:30:46 +00002334 BlockPointerType *New
2335 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002336 Types.push_back(New);
2337 BlockPointerTypes.InsertNode(New, InsertPos);
2338 return QualType(New, 0);
2339}
2340
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002341/// getLValueReferenceType - Return the uniqued reference to the type for an
2342/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002343QualType
2344ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002345 assert(getCanonicalType(T) != OverloadTy &&
2346 "Unresolved overloaded function type");
2347
Bill Wendling3708c182007-05-27 10:15:43 +00002348 // Unique pointers, to guarantee there is only one pointer of a particular
2349 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002350 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002351 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002352
Craig Topper36250ad2014-05-12 05:36:57 +00002353 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002354 if (LValueReferenceType *RT =
2355 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002356 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002357
John McCallfc93cf92009-10-22 22:37:11 +00002358 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2359
Bill Wendling3708c182007-05-27 10:15:43 +00002360 // If the referencee type isn't canonical, this won't be a canonical type
2361 // either, so fill in the canonical type field.
2362 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002363 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2364 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2365 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002366
Bill Wendling3708c182007-05-27 10:15:43 +00002367 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002368 LValueReferenceType *NewIP =
2369 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002370 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002371 }
2372
John McCall90d1c2d2009-09-24 23:30:46 +00002373 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002374 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2375 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002376 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002377 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002378
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002379 return QualType(New, 0);
2380}
2381
2382/// getRValueReferenceType - Return the uniqued reference to the type for an
2383/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002384QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002385 // Unique pointers, to guarantee there is only one pointer of a particular
2386 // structure.
2387 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002388 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002389
Craig Topper36250ad2014-05-12 05:36:57 +00002390 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002391 if (RValueReferenceType *RT =
2392 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2393 return QualType(RT, 0);
2394
John McCallfc93cf92009-10-22 22:37:11 +00002395 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2396
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002397 // If the referencee type isn't canonical, this won't be a canonical type
2398 // either, so fill in the canonical type field.
2399 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002400 if (InnerRef || !T.isCanonical()) {
2401 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2402 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002403
2404 // Get the new insert position for the node we care about.
2405 RValueReferenceType *NewIP =
2406 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002407 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002408 }
2409
John McCall90d1c2d2009-09-24 23:30:46 +00002410 RValueReferenceType *New
2411 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002412 Types.push_back(New);
2413 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002414 return QualType(New, 0);
2415}
2416
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002417/// getMemberPointerType - Return the uniqued reference to the type for a
2418/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002419QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002420 // Unique pointers, to guarantee there is only one pointer of a particular
2421 // structure.
2422 llvm::FoldingSetNodeID ID;
2423 MemberPointerType::Profile(ID, T, Cls);
2424
Craig Topper36250ad2014-05-12 05:36:57 +00002425 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002426 if (MemberPointerType *PT =
2427 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2428 return QualType(PT, 0);
2429
2430 // If the pointee or class type isn't canonical, this won't be a canonical
2431 // type either, so fill in the canonical type field.
2432 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002433 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002434 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2435
2436 // Get the new insert position for the node we care about.
2437 MemberPointerType *NewIP =
2438 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002439 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002440 }
John McCall90d1c2d2009-09-24 23:30:46 +00002441 MemberPointerType *New
2442 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002443 Types.push_back(New);
2444 MemberPointerTypes.InsertNode(New, InsertPos);
2445 return QualType(New, 0);
2446}
2447
Mike Stump11289f42009-09-09 15:08:12 +00002448/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002449/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002450QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002451 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002452 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002453 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002454 assert((EltTy->isDependentType() ||
2455 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002456 "Constant array of VLAs is illegal!");
2457
Chris Lattnere2df3f92009-05-13 04:12:56 +00002458 // Convert the array size into a canonical width matching the pointer size for
2459 // the target.
2460 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002461 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002462 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002463
Chris Lattner23b7eb62007-06-15 23:05:46 +00002464 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002465 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002466
Craig Topper36250ad2014-05-12 05:36:57 +00002467 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002468 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002469 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002470 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002471
John McCall33ddac02011-01-19 10:06:00 +00002472 // If the element type isn't canonical or has qualifiers, this won't
2473 // be a canonical type either, so fill in the canonical type field.
2474 QualType Canon;
2475 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2476 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002477 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002478 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002479 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002480
Chris Lattner36f8e652007-01-27 08:31:04 +00002481 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002482 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002483 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002484 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002485 }
Mike Stump11289f42009-09-09 15:08:12 +00002486
John McCall90d1c2d2009-09-24 23:30:46 +00002487 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002488 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002489 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002490 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002491 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002492}
2493
John McCall06549462011-01-18 08:40:38 +00002494/// getVariableArrayDecayedType - Turns the given type, which may be
2495/// variably-modified, into the corresponding type with all the known
2496/// sizes replaced with [*].
2497QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2498 // Vastly most common case.
2499 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002500
John McCall06549462011-01-18 08:40:38 +00002501 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002502
John McCall06549462011-01-18 08:40:38 +00002503 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002504 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002505 switch (ty->getTypeClass()) {
2506#define TYPE(Class, Base)
2507#define ABSTRACT_TYPE(Class, Base)
2508#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2509#include "clang/AST/TypeNodes.def"
2510 llvm_unreachable("didn't desugar past all non-canonical types?");
2511
2512 // These types should never be variably-modified.
2513 case Type::Builtin:
2514 case Type::Complex:
2515 case Type::Vector:
2516 case Type::ExtVector:
2517 case Type::DependentSizedExtVector:
2518 case Type::ObjCObject:
2519 case Type::ObjCInterface:
2520 case Type::ObjCObjectPointer:
2521 case Type::Record:
2522 case Type::Enum:
2523 case Type::UnresolvedUsing:
2524 case Type::TypeOfExpr:
2525 case Type::TypeOf:
2526 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002527 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002528 case Type::DependentName:
2529 case Type::InjectedClassName:
2530 case Type::TemplateSpecialization:
2531 case Type::DependentTemplateSpecialization:
2532 case Type::TemplateTypeParm:
2533 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002534 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002535 case Type::PackExpansion:
2536 llvm_unreachable("type should never be variably-modified");
2537
2538 // These types can be variably-modified but should never need to
2539 // further decay.
2540 case Type::FunctionNoProto:
2541 case Type::FunctionProto:
2542 case Type::BlockPointer:
2543 case Type::MemberPointer:
2544 return type;
2545
2546 // These types can be variably-modified. All these modifications
2547 // preserve structure except as noted by comments.
2548 // TODO: if we ever care about optimizing VLAs, there are no-op
2549 // optimizations available here.
2550 case Type::Pointer:
2551 result = getPointerType(getVariableArrayDecayedType(
2552 cast<PointerType>(ty)->getPointeeType()));
2553 break;
2554
2555 case Type::LValueReference: {
2556 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2557 result = getLValueReferenceType(
2558 getVariableArrayDecayedType(lv->getPointeeType()),
2559 lv->isSpelledAsLValue());
2560 break;
2561 }
2562
2563 case Type::RValueReference: {
2564 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2565 result = getRValueReferenceType(
2566 getVariableArrayDecayedType(lv->getPointeeType()));
2567 break;
2568 }
2569
Eli Friedman0dfb8892011-10-06 23:00:33 +00002570 case Type::Atomic: {
2571 const AtomicType *at = cast<AtomicType>(ty);
2572 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2573 break;
2574 }
2575
John McCall06549462011-01-18 08:40:38 +00002576 case Type::ConstantArray: {
2577 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2578 result = getConstantArrayType(
2579 getVariableArrayDecayedType(cat->getElementType()),
2580 cat->getSize(),
2581 cat->getSizeModifier(),
2582 cat->getIndexTypeCVRQualifiers());
2583 break;
2584 }
2585
2586 case Type::DependentSizedArray: {
2587 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2588 result = getDependentSizedArrayType(
2589 getVariableArrayDecayedType(dat->getElementType()),
2590 dat->getSizeExpr(),
2591 dat->getSizeModifier(),
2592 dat->getIndexTypeCVRQualifiers(),
2593 dat->getBracketsRange());
2594 break;
2595 }
2596
2597 // Turn incomplete types into [*] types.
2598 case Type::IncompleteArray: {
2599 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2600 result = getVariableArrayType(
2601 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002602 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002603 ArrayType::Normal,
2604 iat->getIndexTypeCVRQualifiers(),
2605 SourceRange());
2606 break;
2607 }
2608
2609 // Turn VLA types into [*] types.
2610 case Type::VariableArray: {
2611 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2612 result = getVariableArrayType(
2613 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002614 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002615 ArrayType::Star,
2616 vat->getIndexTypeCVRQualifiers(),
2617 vat->getBracketsRange());
2618 break;
2619 }
2620 }
2621
2622 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002623 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002624}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002625
Steve Naroffcadebd02007-08-30 18:14:25 +00002626/// getVariableArrayType - Returns a non-unique reference to the type for a
2627/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002628QualType ASTContext::getVariableArrayType(QualType EltTy,
2629 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002630 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002631 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002632 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002633 // Since we don't unique expressions, it isn't possible to unique VLA's
2634 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002635 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002636
John McCall33ddac02011-01-19 10:06:00 +00002637 // Be sure to pull qualifiers off the element type.
2638 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2639 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002640 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002641 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002642 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002643 }
2644
John McCall90d1c2d2009-09-24 23:30:46 +00002645 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002646 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002647
2648 VariableArrayTypes.push_back(New);
2649 Types.push_back(New);
2650 return QualType(New, 0);
2651}
2652
Douglas Gregor4619e432008-12-05 23:32:09 +00002653/// getDependentSizedArrayType - Returns a non-unique reference to
2654/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002655/// type.
John McCall33ddac02011-01-19 10:06:00 +00002656QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2657 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002658 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002659 unsigned elementTypeQuals,
2660 SourceRange brackets) const {
2661 assert((!numElements || numElements->isTypeDependent() ||
2662 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002663 "Size must be type- or value-dependent!");
2664
John McCall33ddac02011-01-19 10:06:00 +00002665 // Dependently-sized array types that do not have a specified number
2666 // of elements will have their sizes deduced from a dependent
2667 // initializer. We do no canonicalization here at all, which is okay
2668 // because they can't be used in most locations.
2669 if (!numElements) {
2670 DependentSizedArrayType *newType
2671 = new (*this, TypeAlignment)
2672 DependentSizedArrayType(*this, elementType, QualType(),
2673 numElements, ASM, elementTypeQuals,
2674 brackets);
2675 Types.push_back(newType);
2676 return QualType(newType, 0);
2677 }
2678
2679 // Otherwise, we actually build a new type every time, but we
2680 // also build a canonical type.
2681
2682 SplitQualType canonElementType = getCanonicalType(elementType).split();
2683
Craig Topper36250ad2014-05-12 05:36:57 +00002684 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002685 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002686 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002687 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002688 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002689
John McCall33ddac02011-01-19 10:06:00 +00002690 // Look for an existing type with these properties.
2691 DependentSizedArrayType *canonTy =
2692 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002693
John McCall33ddac02011-01-19 10:06:00 +00002694 // If we don't have one, build one.
2695 if (!canonTy) {
2696 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002697 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002698 QualType(), numElements, ASM, elementTypeQuals,
2699 brackets);
2700 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2701 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002702 }
2703
John McCall33ddac02011-01-19 10:06:00 +00002704 // Apply qualifiers from the element type to the array.
2705 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002706 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002707
John McCall33ddac02011-01-19 10:06:00 +00002708 // If we didn't need extra canonicalization for the element type,
2709 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002710 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002711 return canon;
2712
2713 // Otherwise, we need to build a type which follows the spelling
2714 // of the element type.
2715 DependentSizedArrayType *sugaredType
2716 = new (*this, TypeAlignment)
2717 DependentSizedArrayType(*this, elementType, canon, numElements,
2718 ASM, elementTypeQuals, brackets);
2719 Types.push_back(sugaredType);
2720 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002721}
2722
John McCall33ddac02011-01-19 10:06:00 +00002723QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002724 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002725 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002726 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002727 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002728
Craig Topper36250ad2014-05-12 05:36:57 +00002729 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002730 if (IncompleteArrayType *iat =
2731 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2732 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002733
2734 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002735 // either, so fill in the canonical type field. We also have to pull
2736 // qualifiers off the element type.
2737 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002738
John McCall33ddac02011-01-19 10:06:00 +00002739 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2740 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002741 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002742 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002743 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002744
2745 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002746 IncompleteArrayType *existing =
2747 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2748 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002749 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002750
John McCall33ddac02011-01-19 10:06:00 +00002751 IncompleteArrayType *newType = new (*this, TypeAlignment)
2752 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002753
John McCall33ddac02011-01-19 10:06:00 +00002754 IncompleteArrayTypes.InsertNode(newType, insertPos);
2755 Types.push_back(newType);
2756 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002757}
2758
Steve Naroff91fcddb2007-07-18 18:00:27 +00002759/// getVectorType - Return the unique reference to a vector type of
2760/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002761QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002762 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002763 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002764
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002765 // Check if we've already instantiated a vector of this type.
2766 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002767 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002768
Craig Topper36250ad2014-05-12 05:36:57 +00002769 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002770 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2771 return QualType(VTP, 0);
2772
2773 // If the element type isn't canonical, this won't be a canonical type either,
2774 // so fill in the canonical type field.
2775 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002776 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002777 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002778
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002779 // Get the new insert position for the node we care about.
2780 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002781 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002782 }
John McCall90d1c2d2009-09-24 23:30:46 +00002783 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002784 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002785 VectorTypes.InsertNode(New, InsertPos);
2786 Types.push_back(New);
2787 return QualType(New, 0);
2788}
2789
Nate Begemance4d7fc2008-04-18 23:10:10 +00002790/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002791/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002792QualType
2793ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002794 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002795
Steve Naroff91fcddb2007-07-18 18:00:27 +00002796 // Check if we've already instantiated a vector of this type.
2797 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002798 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002799 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002800 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002801 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2802 return QualType(VTP, 0);
2803
2804 // If the element type isn't canonical, this won't be a canonical type either,
2805 // so fill in the canonical type field.
2806 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002807 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002808 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002809
Steve Naroff91fcddb2007-07-18 18:00:27 +00002810 // Get the new insert position for the node we care about.
2811 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002812 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002813 }
John McCall90d1c2d2009-09-24 23:30:46 +00002814 ExtVectorType *New = new (*this, TypeAlignment)
2815 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002816 VectorTypes.InsertNode(New, InsertPos);
2817 Types.push_back(New);
2818 return QualType(New, 0);
2819}
2820
Jay Foad39c79802011-01-12 09:06:06 +00002821QualType
2822ASTContext::getDependentSizedExtVectorType(QualType vecType,
2823 Expr *SizeExpr,
2824 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002825 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002826 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002827 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002828
Craig Topper36250ad2014-05-12 05:36:57 +00002829 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002830 DependentSizedExtVectorType *Canon
2831 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2832 DependentSizedExtVectorType *New;
2833 if (Canon) {
2834 // We already have a canonical version of this array type; use it as
2835 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002836 New = new (*this, TypeAlignment)
2837 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2838 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002839 } else {
2840 QualType CanonVecTy = getCanonicalType(vecType);
2841 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002842 New = new (*this, TypeAlignment)
2843 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2844 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002845
2846 DependentSizedExtVectorType *CanonCheck
2847 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2848 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2849 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002850 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2851 } else {
2852 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2853 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002854 New = new (*this, TypeAlignment)
2855 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002856 }
2857 }
Mike Stump11289f42009-09-09 15:08:12 +00002858
Douglas Gregor758a8692009-06-17 21:51:59 +00002859 Types.push_back(New);
2860 return QualType(New, 0);
2861}
2862
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002863/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002864///
Jay Foad39c79802011-01-12 09:06:06 +00002865QualType
2866ASTContext::getFunctionNoProtoType(QualType ResultTy,
2867 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002868 const CallingConv CallConv = Info.getCC();
2869
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002870 // Unique functions, to guarantee there is only one function of a particular
2871 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002872 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002873 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002874
Craig Topper36250ad2014-05-12 05:36:57 +00002875 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002876 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002877 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002878 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002879
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002880 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002881 if (!ResultTy.isCanonical()) {
2882 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002883
Chris Lattner47955de2007-01-27 08:37:20 +00002884 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002885 FunctionNoProtoType *NewIP =
2886 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002887 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002888 }
Mike Stump11289f42009-09-09 15:08:12 +00002889
Roman Divacky65b88cd2011-03-01 17:40:53 +00002890 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002891 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002892 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002893 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002894 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002895 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002896}
2897
Douglas Gregorcd780372013-01-17 23:36:45 +00002898/// \brief Determine whether \p T is canonical as the result type of a function.
2899static bool isCanonicalResultType(QualType T) {
2900 return T.isCanonical() &&
2901 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2902 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2903}
2904
Jay Foad39c79802011-01-12 09:06:06 +00002905QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002906ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002907 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002908 size_t NumArgs = ArgArray.size();
2909
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002910 // Unique functions, to guarantee there is only one function of a particular
2911 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002912 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002913 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2914 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002915
Craig Topper36250ad2014-05-12 05:36:57 +00002916 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002917 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002918 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002919 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002920
2921 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002922 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00002923 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002924 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002925 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002926 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002927 isCanonical = false;
2928
2929 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002930 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002931 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002932 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002933 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002934 CanonicalArgs.reserve(NumArgs);
2935 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002936 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002937
John McCalldb40c7f2010-12-14 08:05:40 +00002938 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002939 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00002940 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002941
Douglas Gregorcd780372013-01-17 23:36:45 +00002942 // Result types do not have ARC lifetime qualifiers.
2943 QualType CanResultTy = getCanonicalType(ResultTy);
2944 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2945 Qualifiers Qs = CanResultTy.getQualifiers();
2946 Qs.removeObjCLifetime();
2947 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2948 }
2949
Jordan Rose5c382722013-03-08 21:51:21 +00002950 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002951
Chris Lattnerfd4de792007-01-27 01:15:32 +00002952 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002953 FunctionProtoType *NewIP =
2954 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002955 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002956 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002957
John McCall31168b02011-06-15 23:02:42 +00002958 // FunctionProtoType objects are allocated with extra bytes after
2959 // them for three variable size arrays at the end:
2960 // - parameter types
2961 // - exception types
2962 // - consumed-arguments flags
2963 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002964 // expression, or information used to resolve the exception
2965 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002966 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002967 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00002968 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2969 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2970 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002971 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00002972 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002973 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00002974 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002975 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002976 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002977 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002978 Size += NumArgs * sizeof(bool);
2979
John McCalldb40c7f2010-12-14 08:05:40 +00002980 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002981 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002982 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002983 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002984 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002985 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002986}
Chris Lattneref51c202006-11-10 07:17:23 +00002987
John McCalle78aac42010-03-10 03:28:59 +00002988#ifndef NDEBUG
2989static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2990 if (!isa<CXXRecordDecl>(D)) return false;
2991 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2992 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2993 return true;
2994 if (RD->getDescribedClassTemplate() &&
2995 !isa<ClassTemplateSpecializationDecl>(RD))
2996 return true;
2997 return false;
2998}
2999#endif
3000
3001/// getInjectedClassNameType - Return the unique reference to the
3002/// injected class name type for the specified templated declaration.
3003QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003004 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003005 assert(NeedsInjectedClassNameType(Decl));
3006 if (Decl->TypeForDecl) {
3007 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003008 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003009 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3010 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3011 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3012 } else {
John McCall424cec92011-01-19 06:33:43 +00003013 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003014 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003015 Decl->TypeForDecl = newType;
3016 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003017 }
3018 return QualType(Decl->TypeForDecl, 0);
3019}
3020
Douglas Gregor83a586e2008-04-13 21:07:44 +00003021/// getTypeDeclType - Return the unique reference to the type for the
3022/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003023QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003024 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003025 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003026
Richard Smithdda56e42011-04-15 14:24:37 +00003027 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003028 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003029
John McCall96f0b5f2010-03-10 06:48:02 +00003030 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3031 "Template type parameter types are always available.");
3032
John McCall81e38502010-02-16 03:57:14 +00003033 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003034 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003035 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003036 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003037 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003038 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003039 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003040 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003041 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003042 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3043 Decl->TypeForDecl = newType;
3044 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003045 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003046 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003047
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003048 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003049}
3050
Chris Lattner32d920b2007-01-26 02:01:53 +00003051/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003052/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003053QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003054ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3055 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003056 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003057
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003058 if (Canonical.isNull())
3059 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003060 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003061 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003062 Decl->TypeForDecl = newType;
3063 Types.push_back(newType);
3064 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003065}
3066
Jay Foad39c79802011-01-12 09:06:06 +00003067QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003068 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3069
Douglas Gregorec9fd132012-01-14 16:38:05 +00003070 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003071 if (PrevDecl->TypeForDecl)
3072 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3073
John McCall424cec92011-01-19 06:33:43 +00003074 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3075 Decl->TypeForDecl = newType;
3076 Types.push_back(newType);
3077 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003078}
3079
Jay Foad39c79802011-01-12 09:06:06 +00003080QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003081 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3082
Douglas Gregorec9fd132012-01-14 16:38:05 +00003083 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003084 if (PrevDecl->TypeForDecl)
3085 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3086
John McCall424cec92011-01-19 06:33:43 +00003087 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3088 Decl->TypeForDecl = newType;
3089 Types.push_back(newType);
3090 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003091}
3092
John McCall81904512011-01-06 01:58:22 +00003093QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3094 QualType modifiedType,
3095 QualType equivalentType) {
3096 llvm::FoldingSetNodeID id;
3097 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3098
Craig Topper36250ad2014-05-12 05:36:57 +00003099 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003100 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3101 if (type) return QualType(type, 0);
3102
3103 QualType canon = getCanonicalType(equivalentType);
3104 type = new (*this, TypeAlignment)
3105 AttributedType(canon, attrKind, modifiedType, equivalentType);
3106
3107 Types.push_back(type);
3108 AttributedTypes.InsertNode(type, insertPos);
3109
3110 return QualType(type, 0);
3111}
3112
3113
John McCallcebee162009-10-18 09:09:24 +00003114/// \brief Retrieve a substitution-result type.
3115QualType
3116ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003117 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003118 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003119 && "replacement types must always be canonical");
3120
3121 llvm::FoldingSetNodeID ID;
3122 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003123 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003124 SubstTemplateTypeParmType *SubstParm
3125 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3126
3127 if (!SubstParm) {
3128 SubstParm = new (*this, TypeAlignment)
3129 SubstTemplateTypeParmType(Parm, Replacement);
3130 Types.push_back(SubstParm);
3131 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3132 }
3133
3134 return QualType(SubstParm, 0);
3135}
3136
Douglas Gregorada4b792011-01-14 02:55:32 +00003137/// \brief Retrieve a
3138QualType ASTContext::getSubstTemplateTypeParmPackType(
3139 const TemplateTypeParmType *Parm,
3140 const TemplateArgument &ArgPack) {
3141#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003142 for (const auto &P : ArgPack.pack_elements()) {
3143 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3144 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003145 }
3146#endif
3147
3148 llvm::FoldingSetNodeID ID;
3149 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003150 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003151 if (SubstTemplateTypeParmPackType *SubstParm
3152 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3153 return QualType(SubstParm, 0);
3154
3155 QualType Canon;
3156 if (!Parm->isCanonicalUnqualified()) {
3157 Canon = getCanonicalType(QualType(Parm, 0));
3158 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3159 ArgPack);
3160 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3161 }
3162
3163 SubstTemplateTypeParmPackType *SubstParm
3164 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3165 ArgPack);
3166 Types.push_back(SubstParm);
3167 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3168 return QualType(SubstParm, 0);
3169}
3170
Douglas Gregoreff93e02009-02-05 23:33:38 +00003171/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003172/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003173/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003174QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003175 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003176 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003177 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003178 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003179 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003180 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003181 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3182
3183 if (TypeParm)
3184 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003185
Chandler Carruth08836322011-05-01 00:51:33 +00003186 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003187 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003188 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003189
3190 TemplateTypeParmType *TypeCheck
3191 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3192 assert(!TypeCheck && "Template type parameter canonical type broken");
3193 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003194 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003195 TypeParm = new (*this, TypeAlignment)
3196 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003197
3198 Types.push_back(TypeParm);
3199 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3200
3201 return QualType(TypeParm, 0);
3202}
3203
John McCalle78aac42010-03-10 03:28:59 +00003204TypeSourceInfo *
3205ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3206 SourceLocation NameLoc,
3207 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003208 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003209 assert(!Name.getAsDependentTemplateName() &&
3210 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003211 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003212
3213 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003214 TemplateSpecializationTypeLoc TL =
3215 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003216 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003217 TL.setTemplateNameLoc(NameLoc);
3218 TL.setLAngleLoc(Args.getLAngleLoc());
3219 TL.setRAngleLoc(Args.getRAngleLoc());
3220 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3221 TL.setArgLocInfo(i, Args[i].getLocInfo());
3222 return DI;
3223}
3224
Mike Stump11289f42009-09-09 15:08:12 +00003225QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003226ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003227 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003228 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003229 assert(!Template.getAsDependentTemplateName() &&
3230 "No dependent template names here!");
3231
John McCall6b51f282009-11-23 01:53:49 +00003232 unsigned NumArgs = Args.size();
3233
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003234 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003235 ArgVec.reserve(NumArgs);
3236 for (unsigned i = 0; i != NumArgs; ++i)
3237 ArgVec.push_back(Args[i].getArgument());
3238
John McCall2408e322010-04-27 00:57:59 +00003239 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003240 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003241}
3242
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003243#ifndef NDEBUG
3244static bool hasAnyPackExpansions(const TemplateArgument *Args,
3245 unsigned NumArgs) {
3246 for (unsigned I = 0; I != NumArgs; ++I)
3247 if (Args[I].isPackExpansion())
3248 return true;
3249
3250 return true;
3251}
3252#endif
3253
John McCall0ad16662009-10-29 08:12:44 +00003254QualType
3255ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003256 const TemplateArgument *Args,
3257 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003258 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003259 assert(!Template.getAsDependentTemplateName() &&
3260 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003261 // Look through qualified template names.
3262 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3263 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003264
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003265 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003266 Template.getAsTemplateDecl() &&
3267 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003268 QualType CanonType;
3269 if (!Underlying.isNull())
3270 CanonType = getCanonicalType(Underlying);
3271 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003272 // We can get here with an alias template when the specialization contains
3273 // a pack expansion that does not match up with a parameter pack.
3274 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3275 "Caller must compute aliased type");
3276 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003277 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3278 NumArgs);
3279 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003280
Douglas Gregora8e02e72009-07-28 23:00:59 +00003281 // Allocate the (non-canonical) template specialization type, but don't
3282 // try to unique it: these types typically have location information that
3283 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003284 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3285 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003286 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003287 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003288 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003289 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3290 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003291
Douglas Gregor8bf42052009-02-09 18:46:07 +00003292 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003293 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003294}
3295
Mike Stump11289f42009-09-09 15:08:12 +00003296QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003297ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3298 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003299 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003300 assert(!Template.getAsDependentTemplateName() &&
3301 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003302
Douglas Gregore29139c2011-03-03 17:04:51 +00003303 // Look through qualified template names.
3304 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3305 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003306
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003307 // Build the canonical template specialization type.
3308 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003309 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003310 CanonArgs.reserve(NumArgs);
3311 for (unsigned I = 0; I != NumArgs; ++I)
3312 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3313
3314 // Determine whether this canonical template specialization type already
3315 // exists.
3316 llvm::FoldingSetNodeID ID;
3317 TemplateSpecializationType::Profile(ID, CanonTemplate,
3318 CanonArgs.data(), NumArgs, *this);
3319
Craig Topper36250ad2014-05-12 05:36:57 +00003320 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003321 TemplateSpecializationType *Spec
3322 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3323
3324 if (!Spec) {
3325 // Allocate a new canonical template specialization type.
3326 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3327 sizeof(TemplateArgument) * NumArgs),
3328 TypeAlignment);
3329 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3330 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003331 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003332 Types.push_back(Spec);
3333 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3334 }
3335
3336 assert(Spec->isDependentType() &&
3337 "Non-dependent template-id type must have a canonical type");
3338 return QualType(Spec, 0);
3339}
3340
3341QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003342ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3343 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003344 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003345 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003346 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003347
Craig Topper36250ad2014-05-12 05:36:57 +00003348 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003349 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003350 if (T)
3351 return QualType(T, 0);
3352
Douglas Gregorc42075a2010-02-04 18:10:26 +00003353 QualType Canon = NamedType;
3354 if (!Canon.isCanonical()) {
3355 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003356 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3357 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003358 (void)CheckT;
3359 }
3360
Abramo Bagnara6150c882010-05-11 21:36:43 +00003361 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003362 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003363 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003364 return QualType(T, 0);
3365}
3366
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003367QualType
Jay Foad39c79802011-01-12 09:06:06 +00003368ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003369 llvm::FoldingSetNodeID ID;
3370 ParenType::Profile(ID, InnerType);
3371
Craig Topper36250ad2014-05-12 05:36:57 +00003372 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003373 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3374 if (T)
3375 return QualType(T, 0);
3376
3377 QualType Canon = InnerType;
3378 if (!Canon.isCanonical()) {
3379 Canon = getCanonicalType(InnerType);
3380 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3381 assert(!CheckT && "Paren canonical type broken");
3382 (void)CheckT;
3383 }
3384
3385 T = new (*this) ParenType(InnerType, Canon);
3386 Types.push_back(T);
3387 ParenTypes.InsertNode(T, InsertPos);
3388 return QualType(T, 0);
3389}
3390
Douglas Gregor02085352010-03-31 20:19:30 +00003391QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3392 NestedNameSpecifier *NNS,
3393 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003394 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003395 if (Canon.isNull()) {
3396 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003397 ElaboratedTypeKeyword CanonKeyword = Keyword;
3398 if (Keyword == ETK_None)
3399 CanonKeyword = ETK_Typename;
3400
3401 if (CanonNNS != NNS || CanonKeyword != Keyword)
3402 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003403 }
3404
3405 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003406 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003407
Craig Topper36250ad2014-05-12 05:36:57 +00003408 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003409 DependentNameType *T
3410 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003411 if (T)
3412 return QualType(T, 0);
3413
Douglas Gregor02085352010-03-31 20:19:30 +00003414 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003415 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003416 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003417 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003418}
3419
Mike Stump11289f42009-09-09 15:08:12 +00003420QualType
John McCallc392f372010-06-11 00:33:02 +00003421ASTContext::getDependentTemplateSpecializationType(
3422 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003423 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003424 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003425 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003426 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003427 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003428 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3429 ArgCopy.push_back(Args[I].getArgument());
3430 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3431 ArgCopy.size(),
3432 ArgCopy.data());
3433}
3434
3435QualType
3436ASTContext::getDependentTemplateSpecializationType(
3437 ElaboratedTypeKeyword Keyword,
3438 NestedNameSpecifier *NNS,
3439 const IdentifierInfo *Name,
3440 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003441 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003442 assert((!NNS || NNS->isDependent()) &&
3443 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003444
Douglas Gregorc42075a2010-02-04 18:10:26 +00003445 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003446 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3447 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003448
Craig Topper36250ad2014-05-12 05:36:57 +00003449 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003450 DependentTemplateSpecializationType *T
3451 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003452 if (T)
3453 return QualType(T, 0);
3454
John McCallc392f372010-06-11 00:33:02 +00003455 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003456
John McCallc392f372010-06-11 00:33:02 +00003457 ElaboratedTypeKeyword CanonKeyword = Keyword;
3458 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3459
3460 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003461 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003462 for (unsigned I = 0; I != NumArgs; ++I) {
3463 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3464 if (!CanonArgs[I].structurallyEquals(Args[I]))
3465 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003466 }
3467
John McCallc392f372010-06-11 00:33:02 +00003468 QualType Canon;
3469 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3470 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3471 Name, NumArgs,
3472 CanonArgs.data());
3473
3474 // Find the insert position again.
3475 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3476 }
3477
3478 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3479 sizeof(TemplateArgument) * NumArgs),
3480 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003481 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003482 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003483 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003484 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003485 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003486}
3487
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003488QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003489 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003490 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003491 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003492
3493 assert(Pattern->containsUnexpandedParameterPack() &&
3494 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003495 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003496 PackExpansionType *T
3497 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3498 if (T)
3499 return QualType(T, 0);
3500
3501 QualType Canon;
3502 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003503 Canon = getCanonicalType(Pattern);
3504 // The canonical type might not contain an unexpanded parameter pack, if it
3505 // contains an alias template specialization which ignores one of its
3506 // parameters.
3507 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003508 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003509
Richard Smith68eea502012-07-16 00:20:35 +00003510 // Find the insert position again, in case we inserted an element into
3511 // PackExpansionTypes and invalidated our insert position.
3512 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3513 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003514 }
3515
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003516 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003517 Types.push_back(T);
3518 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003519 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003520}
3521
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003522/// CmpProtocolNames - Comparison predicate for sorting protocols
3523/// alphabetically.
3524static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3525 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003526 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003527}
3528
John McCall8b07ec22010-05-15 11:32:37 +00003529static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003530 unsigned NumProtocols) {
3531 if (NumProtocols == 0) return true;
3532
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003533 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3534 return false;
3535
John McCallfc93cf92009-10-22 22:37:11 +00003536 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003537 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3538 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003539 return false;
3540 return true;
3541}
3542
3543static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003544 unsigned &NumProtocols) {
3545 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003546
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003547 // Sort protocols, keyed by name.
3548 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3549
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003550 // Canonicalize.
3551 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3552 Protocols[I] = Protocols[I]->getCanonicalDecl();
3553
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003554 // Remove duplicates.
3555 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3556 NumProtocols = ProtocolsEnd-Protocols;
3557}
3558
John McCall8b07ec22010-05-15 11:32:37 +00003559QualType ASTContext::getObjCObjectType(QualType BaseType,
3560 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003561 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003562 // If the base type is an interface and there aren't any protocols
3563 // to add, then the interface type will do just fine.
3564 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3565 return BaseType;
3566
3567 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003568 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003569 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Craig Topper36250ad2014-05-12 05:36:57 +00003570 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003571 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3572 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003573
John McCall8b07ec22010-05-15 11:32:37 +00003574 // Build the canonical type, which has the canonical base type and
3575 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003576 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003577 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3578 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3579 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003580 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003581 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003582 unsigned UniqueCount = NumProtocols;
3583
John McCallfc93cf92009-10-22 22:37:11 +00003584 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003585 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3586 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003587 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003588 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3589 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003590 }
3591
3592 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003593 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3594 }
3595
3596 unsigned Size = sizeof(ObjCObjectTypeImpl);
3597 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3598 void *Mem = Allocate(Size, TypeAlignment);
3599 ObjCObjectTypeImpl *T =
3600 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3601
3602 Types.push_back(T);
3603 ObjCObjectTypes.InsertNode(T, InsertPos);
3604 return QualType(T, 0);
3605}
3606
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003607/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3608/// protocol list adopt all protocols in QT's qualified-id protocol
3609/// list.
3610bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3611 ObjCInterfaceDecl *IC) {
3612 if (!QT->isObjCQualifiedIdType())
3613 return false;
3614
3615 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3616 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003617 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003618 if (!IC->ClassImplementsProtocol(Proto, false))
3619 return false;
3620 }
3621 return true;
3622 }
3623 return false;
3624}
3625
3626/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3627/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3628/// of protocols.
3629bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3630 ObjCInterfaceDecl *IDecl) {
3631 if (!QT->isObjCQualifiedIdType())
3632 return false;
3633 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3634 if (!OPT)
3635 return false;
3636 if (!IDecl->hasDefinition())
3637 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003638 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3639 CollectInheritedProtocols(IDecl, InheritedProtocols);
3640 if (InheritedProtocols.empty())
3641 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003642 // Check that if every protocol in list of id<plist> conforms to a protcol
3643 // of IDecl's, then bridge casting is ok.
3644 bool Conforms = false;
3645 for (auto *Proto : OPT->quals()) {
3646 Conforms = false;
3647 for (auto *PI : InheritedProtocols) {
3648 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3649 Conforms = true;
3650 break;
3651 }
3652 }
3653 if (!Conforms)
3654 break;
3655 }
3656 if (Conforms)
3657 return true;
3658
Aaron Ballman83731462014-03-17 16:14:00 +00003659 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003660 // If both the right and left sides have qualifiers.
3661 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003662 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003663 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003664 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003665 break;
3666 }
3667 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003668 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003669 }
3670 return true;
3671}
3672
John McCall8b07ec22010-05-15 11:32:37 +00003673/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3674/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003675QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003676 llvm::FoldingSetNodeID ID;
3677 ObjCObjectPointerType::Profile(ID, ObjectT);
3678
Craig Topper36250ad2014-05-12 05:36:57 +00003679 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003680 if (ObjCObjectPointerType *QT =
3681 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3682 return QualType(QT, 0);
3683
3684 // Find the canonical object type.
3685 QualType Canonical;
3686 if (!ObjectT.isCanonical()) {
3687 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3688
3689 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003690 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3691 }
3692
Douglas Gregorf85bee62010-02-08 22:59:26 +00003693 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003694 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3695 ObjCObjectPointerType *QType =
3696 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003697
Steve Narofffb4330f2009-06-17 22:40:22 +00003698 Types.push_back(QType);
3699 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003700 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003701}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003702
Douglas Gregor1c283312010-08-11 12:19:30 +00003703/// getObjCInterfaceType - Return the unique reference to the type for the
3704/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003705QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3706 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003707 if (Decl->TypeForDecl)
3708 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003709
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003710 if (PrevDecl) {
3711 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3712 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3713 return QualType(PrevDecl->TypeForDecl, 0);
3714 }
3715
Douglas Gregor7671e532011-12-16 16:34:57 +00003716 // Prefer the definition, if there is one.
3717 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3718 Decl = Def;
3719
Douglas Gregor1c283312010-08-11 12:19:30 +00003720 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3721 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3722 Decl->TypeForDecl = T;
3723 Types.push_back(T);
3724 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003725}
3726
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003727/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3728/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003729/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003730/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003731/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003732QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003733 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003734 if (tofExpr->isTypeDependent()) {
3735 llvm::FoldingSetNodeID ID;
3736 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003737
Craig Topper36250ad2014-05-12 05:36:57 +00003738 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003739 DependentTypeOfExprType *Canon
3740 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3741 if (Canon) {
3742 // We already have a "canonical" version of an identical, dependent
3743 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003744 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003745 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003746 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003747 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003748 Canon
3749 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003750 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3751 toe = Canon;
3752 }
3753 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003754 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003755 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003756 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003757 Types.push_back(toe);
3758 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003759}
3760
Steve Naroffa773cd52007-08-01 18:02:17 +00003761/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003762/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003763/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003764/// an issue. This doesn't affect the type checker, since it operates
3765/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003766QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003767 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003768 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003769 Types.push_back(tot);
3770 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003771}
3772
Anders Carlssonad6bd352009-06-24 21:24:56 +00003773
Richard Smith8eb1d322014-06-05 20:13:13 +00003774/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3775/// nodes. This would never be helpful, since each such type has its own
3776/// expression, and would not give a significant memory saving, since there
3777/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003778QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003779 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003780
3781 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003782 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003783 // unique dependent type. Two such decltype-specifiers refer to the same
3784 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003785 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003786 llvm::FoldingSetNodeID ID;
3787 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003788
Craig Topper36250ad2014-05-12 05:36:57 +00003789 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003790 DependentDecltypeType *Canon
3791 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003792 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003793 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003794 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003795 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003796 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003797 dt = new (*this, TypeAlignment)
3798 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003799 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003800 dt = new (*this, TypeAlignment)
3801 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003802 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003803 Types.push_back(dt);
3804 return QualType(dt, 0);
3805}
3806
Alexis Hunte852b102011-05-24 22:41:36 +00003807/// getUnaryTransformationType - We don't unique these, since the memory
3808/// savings are minimal and these are rare.
3809QualType ASTContext::getUnaryTransformType(QualType BaseType,
3810 QualType UnderlyingType,
3811 UnaryTransformType::UTTKind Kind)
3812 const {
3813 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003814 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3815 Kind,
3816 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003817 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003818 Types.push_back(Ty);
3819 return QualType(Ty, 0);
3820}
3821
Richard Smith2a7d4812013-05-04 07:00:32 +00003822/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3823/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3824/// canonical deduced-but-dependent 'auto' type.
3825QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003826 bool IsDependent) const {
3827 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003828 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003829
Richard Smith2a7d4812013-05-04 07:00:32 +00003830 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003831 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003832 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003833 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003834 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3835 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003836
Richard Smith74aeef52013-04-26 16:15:35 +00003837 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003838 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003839 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003840 Types.push_back(AT);
3841 if (InsertPos)
3842 AutoTypes.InsertNode(AT, InsertPos);
3843 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003844}
3845
Eli Friedman0dfb8892011-10-06 23:00:33 +00003846/// getAtomicType - Return the uniqued reference to the atomic type for
3847/// the given value type.
3848QualType ASTContext::getAtomicType(QualType T) const {
3849 // Unique pointers, to guarantee there is only one pointer of a particular
3850 // structure.
3851 llvm::FoldingSetNodeID ID;
3852 AtomicType::Profile(ID, T);
3853
Craig Topper36250ad2014-05-12 05:36:57 +00003854 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003855 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3856 return QualType(AT, 0);
3857
3858 // If the atomic value type isn't canonical, this won't be a canonical type
3859 // either, so fill in the canonical type field.
3860 QualType Canonical;
3861 if (!T.isCanonical()) {
3862 Canonical = getAtomicType(getCanonicalType(T));
3863
3864 // Get the new insert position for the node we care about.
3865 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003866 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003867 }
3868 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3869 Types.push_back(New);
3870 AtomicTypes.InsertNode(New, InsertPos);
3871 return QualType(New, 0);
3872}
3873
Richard Smith02e85f32011-04-14 22:09:26 +00003874/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3875QualType ASTContext::getAutoDeductType() const {
3876 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003877 AutoDeductTy = QualType(
3878 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003879 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003880 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003881 return AutoDeductTy;
3882}
3883
3884/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3885QualType ASTContext::getAutoRRefDeductType() const {
3886 if (AutoRRefDeductTy.isNull())
3887 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3888 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3889 return AutoRRefDeductTy;
3890}
3891
Chris Lattnerfb072462007-01-23 05:45:31 +00003892/// getTagDeclType - Return the unique reference to the type for the
3893/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003894QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003895 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003896 // FIXME: What is the design on getTagDeclType when it requires casting
3897 // away const? mutable?
3898 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003899}
3900
Mike Stump11289f42009-09-09 15:08:12 +00003901/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3902/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3903/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003904CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003905 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003906}
Chris Lattnerfb072462007-01-23 05:45:31 +00003907
Hans Wennborg27541db2011-10-27 08:29:09 +00003908/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3909CanQualType ASTContext::getIntMaxType() const {
3910 return getFromTargetType(Target->getIntMaxType());
3911}
3912
3913/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3914CanQualType ASTContext::getUIntMaxType() const {
3915 return getFromTargetType(Target->getUIntMaxType());
3916}
3917
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003918/// getSignedWCharType - Return the type of "signed wchar_t".
3919/// Used when in C++, as a GCC extension.
3920QualType ASTContext::getSignedWCharType() const {
3921 // FIXME: derive from "Target" ?
3922 return WCharTy;
3923}
3924
3925/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3926/// Used when in C++, as a GCC extension.
3927QualType ASTContext::getUnsignedWCharType() const {
3928 // FIXME: derive from "Target" ?
3929 return UnsignedIntTy;
3930}
3931
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003932QualType ASTContext::getIntPtrType() const {
3933 return getFromTargetType(Target->getIntPtrType());
3934}
3935
3936QualType ASTContext::getUIntPtrType() const {
3937 return getCorrespondingUnsignedType(getIntPtrType());
3938}
3939
Hans Wennborg27541db2011-10-27 08:29:09 +00003940/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003941/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3942QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003943 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003944}
3945
Eli Friedman4e91899e2012-11-27 02:58:24 +00003946/// \brief Return the unique type for "pid_t" defined in
3947/// <sys/types.h>. We need this to compute the correct type for vfork().
3948QualType ASTContext::getProcessIDType() const {
3949 return getFromTargetType(Target->getProcessIDType());
3950}
3951
Chris Lattnera21ad802008-04-02 05:18:44 +00003952//===----------------------------------------------------------------------===//
3953// Type Operators
3954//===----------------------------------------------------------------------===//
3955
Jay Foad39c79802011-01-12 09:06:06 +00003956CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003957 // Push qualifiers into arrays, and then discard any remaining
3958 // qualifiers.
3959 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003960 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003961 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003962 QualType Result;
3963 if (isa<ArrayType>(Ty)) {
3964 Result = getArrayDecayedType(QualType(Ty,0));
3965 } else if (isa<FunctionType>(Ty)) {
3966 Result = getPointerType(QualType(Ty, 0));
3967 } else {
3968 Result = QualType(Ty, 0);
3969 }
3970
3971 return CanQualType::CreateUnsafe(Result);
3972}
3973
John McCall6c9dd522011-01-18 07:41:22 +00003974QualType ASTContext::getUnqualifiedArrayType(QualType type,
3975 Qualifiers &quals) {
3976 SplitQualType splitType = type.getSplitUnqualifiedType();
3977
3978 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3979 // the unqualified desugared type and then drops it on the floor.
3980 // We then have to strip that sugar back off with
3981 // getUnqualifiedDesugaredType(), which is silly.
3982 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003983 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003984
3985 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003986 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003987 quals = splitType.Quals;
3988 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003989 }
3990
John McCall6c9dd522011-01-18 07:41:22 +00003991 // Otherwise, recurse on the array's element type.
3992 QualType elementType = AT->getElementType();
3993 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3994
3995 // If that didn't change the element type, AT has no qualifiers, so we
3996 // can just use the results in splitType.
3997 if (elementType == unqualElementType) {
3998 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003999 quals = splitType.Quals;
4000 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004001 }
4002
4003 // Otherwise, add in the qualifiers from the outermost type, then
4004 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004005 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004006
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004007 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004008 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004009 CAT->getSizeModifier(), 0);
4010 }
4011
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004012 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004013 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004014 }
4015
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004016 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004017 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004018 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004019 VAT->getSizeModifier(),
4020 VAT->getIndexTypeCVRQualifiers(),
4021 VAT->getBracketsRange());
4022 }
4023
4024 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004025 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004026 DSAT->getSizeModifier(), 0,
4027 SourceRange());
4028}
4029
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004030/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4031/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4032/// they point to and return true. If T1 and T2 aren't pointer types
4033/// or pointer-to-member types, or if they are not similar at this
4034/// level, returns false and leaves T1 and T2 unchanged. Top-level
4035/// qualifiers on T1 and T2 are ignored. This function will typically
4036/// be called in a loop that successively "unwraps" pointer and
4037/// pointer-to-member types to compare them at each level.
4038bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4039 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4040 *T2PtrType = T2->getAs<PointerType>();
4041 if (T1PtrType && T2PtrType) {
4042 T1 = T1PtrType->getPointeeType();
4043 T2 = T2PtrType->getPointeeType();
4044 return true;
4045 }
4046
4047 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4048 *T2MPType = T2->getAs<MemberPointerType>();
4049 if (T1MPType && T2MPType &&
4050 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4051 QualType(T2MPType->getClass(), 0))) {
4052 T1 = T1MPType->getPointeeType();
4053 T2 = T2MPType->getPointeeType();
4054 return true;
4055 }
4056
David Blaikiebbafb8a2012-03-11 07:00:24 +00004057 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004058 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4059 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4060 if (T1OPType && T2OPType) {
4061 T1 = T1OPType->getPointeeType();
4062 T2 = T2OPType->getPointeeType();
4063 return true;
4064 }
4065 }
4066
4067 // FIXME: Block pointers, too?
4068
4069 return false;
4070}
4071
Jay Foad39c79802011-01-12 09:06:06 +00004072DeclarationNameInfo
4073ASTContext::getNameForTemplate(TemplateName Name,
4074 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004075 switch (Name.getKind()) {
4076 case TemplateName::QualifiedTemplate:
4077 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004078 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004079 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4080 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004081
John McCalld9dfe3a2011-06-30 08:33:18 +00004082 case TemplateName::OverloadedTemplate: {
4083 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4084 // DNInfo work in progress: CHECKME: what about DNLoc?
4085 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4086 }
4087
4088 case TemplateName::DependentTemplate: {
4089 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004090 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004091 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004092 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4093 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004094 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004095 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4096 // DNInfo work in progress: FIXME: source locations?
4097 DeclarationNameLoc DNLoc;
4098 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4099 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4100 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004101 }
4102 }
4103
John McCalld9dfe3a2011-06-30 08:33:18 +00004104 case TemplateName::SubstTemplateTemplateParm: {
4105 SubstTemplateTemplateParmStorage *subst
4106 = Name.getAsSubstTemplateTemplateParm();
4107 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4108 NameLoc);
4109 }
4110
4111 case TemplateName::SubstTemplateTemplateParmPack: {
4112 SubstTemplateTemplateParmPackStorage *subst
4113 = Name.getAsSubstTemplateTemplateParmPack();
4114 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4115 NameLoc);
4116 }
4117 }
4118
4119 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004120}
4121
Jay Foad39c79802011-01-12 09:06:06 +00004122TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004123 switch (Name.getKind()) {
4124 case TemplateName::QualifiedTemplate:
4125 case TemplateName::Template: {
4126 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004127 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004128 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004129 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4130
4131 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004132 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004133 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004134
John McCalld9dfe3a2011-06-30 08:33:18 +00004135 case TemplateName::OverloadedTemplate:
4136 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004137
John McCalld9dfe3a2011-06-30 08:33:18 +00004138 case TemplateName::DependentTemplate: {
4139 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4140 assert(DTN && "Non-dependent template names must refer to template decls.");
4141 return DTN->CanonicalTemplateName;
4142 }
4143
4144 case TemplateName::SubstTemplateTemplateParm: {
4145 SubstTemplateTemplateParmStorage *subst
4146 = Name.getAsSubstTemplateTemplateParm();
4147 return getCanonicalTemplateName(subst->getReplacement());
4148 }
4149
4150 case TemplateName::SubstTemplateTemplateParmPack: {
4151 SubstTemplateTemplateParmPackStorage *subst
4152 = Name.getAsSubstTemplateTemplateParmPack();
4153 TemplateTemplateParmDecl *canonParameter
4154 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4155 TemplateArgument canonArgPack
4156 = getCanonicalTemplateArgument(subst->getArgumentPack());
4157 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4158 }
4159 }
4160
4161 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004162}
4163
Douglas Gregoradee3e32009-11-11 23:06:43 +00004164bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4165 X = getCanonicalTemplateName(X);
4166 Y = getCanonicalTemplateName(Y);
4167 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4168}
4169
Mike Stump11289f42009-09-09 15:08:12 +00004170TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004171ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004172 switch (Arg.getKind()) {
4173 case TemplateArgument::Null:
4174 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004175
Douglas Gregora8e02e72009-07-28 23:00:59 +00004176 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004177 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004178
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004179 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004180 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004181 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004182 }
Mike Stump11289f42009-09-09 15:08:12 +00004183
Eli Friedmanb826a002012-09-26 02:36:12 +00004184 case TemplateArgument::NullPtr:
4185 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4186 /*isNullPtr*/true);
4187
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004188 case TemplateArgument::Template:
4189 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004190
4191 case TemplateArgument::TemplateExpansion:
4192 return TemplateArgument(getCanonicalTemplateName(
4193 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004194 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004195
Douglas Gregora8e02e72009-07-28 23:00:59 +00004196 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004197 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004198
Douglas Gregora8e02e72009-07-28 23:00:59 +00004199 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004200 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004201
Douglas Gregora8e02e72009-07-28 23:00:59 +00004202 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004203 if (Arg.pack_size() == 0)
4204 return Arg;
4205
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004206 TemplateArgument *CanonArgs
4207 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004208 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004209 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004210 AEnd = Arg.pack_end();
4211 A != AEnd; (void)++A, ++Idx)
4212 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004213
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004214 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004215 }
4216 }
4217
4218 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004219 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004220}
4221
Douglas Gregor333489b2009-03-27 23:10:48 +00004222NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004223ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004224 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004225 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004226
4227 switch (NNS->getKind()) {
4228 case NestedNameSpecifier::Identifier:
4229 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004230 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004231 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4232 NNS->getAsIdentifier());
4233
4234 case NestedNameSpecifier::Namespace:
4235 // A namespace is canonical; build a nested-name-specifier with
4236 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004237 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004238 NNS->getAsNamespace()->getOriginalNamespace());
4239
4240 case NestedNameSpecifier::NamespaceAlias:
4241 // A namespace is canonical; build a nested-name-specifier with
4242 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004243 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004244 NNS->getAsNamespaceAlias()->getNamespace()
4245 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004246
4247 case NestedNameSpecifier::TypeSpec:
4248 case NestedNameSpecifier::TypeSpecWithTemplate: {
4249 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004250
4251 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4252 // break it apart into its prefix and identifier, then reconsititute those
4253 // as the canonical nested-name-specifier. This is required to canonicalize
4254 // a dependent nested-name-specifier involving typedefs of dependent-name
4255 // types, e.g.,
4256 // typedef typename T::type T1;
4257 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004258 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4259 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004260 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004261
Eli Friedman5358a0a2012-03-03 04:09:56 +00004262 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4263 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4264 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004265 return NestedNameSpecifier::Create(*this, nullptr, false,
4266 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004267 }
4268
4269 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004270 case NestedNameSpecifier::Super:
4271 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004272 return NNS;
4273 }
4274
David Blaikie8a40f702012-01-17 06:56:22 +00004275 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004276}
4277
Chris Lattner7adf0762008-08-04 07:31:14 +00004278
Jay Foad39c79802011-01-12 09:06:06 +00004279const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004280 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004281 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004282 // Handle the common positive case fast.
4283 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4284 return AT;
4285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
John McCall8ccfcb52009-09-24 19:53:00 +00004287 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004288 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004289 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004290
John McCall8ccfcb52009-09-24 19:53:00 +00004291 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004292 // implements C99 6.7.3p8: "If the specification of an array type includes
4293 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004294
Chris Lattner7adf0762008-08-04 07:31:14 +00004295 // If we get here, we either have type qualifiers on the type, or we have
4296 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004297 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004298
John McCall33ddac02011-01-19 10:06:00 +00004299 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004300 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004301
Chris Lattner7adf0762008-08-04 07:31:14 +00004302 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004303 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004304 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004305 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004306
Chris Lattner7adf0762008-08-04 07:31:14 +00004307 // Otherwise, we have an array and we have qualifiers on it. Push the
4308 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004309 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004310
Chris Lattner7adf0762008-08-04 07:31:14 +00004311 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4312 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4313 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004314 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004315 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4316 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4317 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004318 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004319
Mike Stump11289f42009-09-09 15:08:12 +00004320 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004321 = dyn_cast<DependentSizedArrayType>(ATy))
4322 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004323 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004324 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004325 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004326 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004327 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004328
Chris Lattner7adf0762008-08-04 07:31:14 +00004329 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004330 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004331 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004332 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004333 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004334 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004335}
4336
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004337QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004338 if (T->isArrayType() || T->isFunctionType())
4339 return getDecayedType(T);
4340 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004341}
4342
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004343QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004344 T = getVariableArrayDecayedType(T);
4345 T = getAdjustedParameterType(T);
4346 return T.getUnqualifiedType();
4347}
4348
David Majnemerd09a51c2015-03-03 01:50:05 +00004349QualType ASTContext::getExceptionObjectType(QualType T) const {
4350 // C++ [except.throw]p3:
4351 // A throw-expression initializes a temporary object, called the exception
4352 // object, the type of which is determined by removing any top-level
4353 // cv-qualifiers from the static type of the operand of throw and adjusting
4354 // the type from "array of T" or "function returning T" to "pointer to T"
4355 // or "pointer to function returning T", [...]
4356 T = getVariableArrayDecayedType(T);
4357 if (T->isArrayType() || T->isFunctionType())
4358 T = getDecayedType(T);
4359 return T.getUnqualifiedType();
4360}
4361
Chris Lattnera21ad802008-04-02 05:18:44 +00004362/// getArrayDecayedType - Return the properly qualified result of decaying the
4363/// specified array type to a pointer. This operation is non-trivial when
4364/// handling typedefs etc. The canonical type of "T" must be an array type,
4365/// this returns a pointer to a properly qualified element of the array.
4366///
4367/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004368QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004369 // Get the element type with 'getAsArrayType' so that we don't lose any
4370 // typedefs in the element type of the array. This also handles propagation
4371 // of type qualifiers from the array type into the element type if present
4372 // (C99 6.7.3p8).
4373 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4374 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004375
Chris Lattner7adf0762008-08-04 07:31:14 +00004376 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004377
4378 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004379 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004380}
4381
John McCall33ddac02011-01-19 10:06:00 +00004382QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4383 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004384}
4385
John McCall33ddac02011-01-19 10:06:00 +00004386QualType ASTContext::getBaseElementType(QualType type) const {
4387 Qualifiers qs;
4388 while (true) {
4389 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004390 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004391 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004392
John McCall33ddac02011-01-19 10:06:00 +00004393 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004394 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004395 }
Mike Stump11289f42009-09-09 15:08:12 +00004396
John McCall33ddac02011-01-19 10:06:00 +00004397 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004398}
4399
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004400/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004401uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004402ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4403 uint64_t ElementCount = 1;
4404 do {
4405 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004406 CA = dyn_cast_or_null<ConstantArrayType>(
4407 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004408 } while (CA);
4409 return ElementCount;
4410}
4411
Steve Naroff0af91202007-04-27 21:51:21 +00004412/// getFloatingRank - Return a relative rank for floating point types.
4413/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004414static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004415 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004416 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004417
John McCall9dd450b2009-09-21 23:43:11 +00004418 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4419 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004420 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004421 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004422 case BuiltinType::Float: return FloatRank;
4423 case BuiltinType::Double: return DoubleRank;
4424 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004425 }
4426}
4427
Mike Stump11289f42009-09-09 15:08:12 +00004428/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4429/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004430/// 'typeDomain' is a real floating point or complex type.
4431/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004432QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4433 QualType Domain) const {
4434 FloatingRank EltRank = getFloatingRank(Size);
4435 if (Domain->isComplexType()) {
4436 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004437 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004438 case FloatRank: return FloatComplexTy;
4439 case DoubleRank: return DoubleComplexTy;
4440 case LongDoubleRank: return LongDoubleComplexTy;
4441 }
Steve Naroff0af91202007-04-27 21:51:21 +00004442 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004443
4444 assert(Domain->isRealFloatingType() && "Unknown domain!");
4445 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004446 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004447 case FloatRank: return FloatTy;
4448 case DoubleRank: return DoubleTy;
4449 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004450 }
David Blaikief47fa302012-01-17 02:30:50 +00004451 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004452}
4453
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004454/// getFloatingTypeOrder - Compare the rank of the two specified floating
4455/// point types, ignoring the domain of the type (i.e. 'double' ==
4456/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004457/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004458int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004459 FloatingRank LHSR = getFloatingRank(LHS);
4460 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004461
Chris Lattnerb90739d2008-04-06 23:38:49 +00004462 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004463 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004464 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004465 return 1;
4466 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004467}
4468
Chris Lattner76a00cf2008-04-06 22:59:24 +00004469/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4470/// routine will assert if passed a built-in type that isn't an integer or enum,
4471/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004472unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004473 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004474
Chris Lattner76a00cf2008-04-06 22:59:24 +00004475 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004476 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004477 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004478 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004479 case BuiltinType::Char_S:
4480 case BuiltinType::Char_U:
4481 case BuiltinType::SChar:
4482 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004483 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004484 case BuiltinType::Short:
4485 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004486 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004487 case BuiltinType::Int:
4488 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004489 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004490 case BuiltinType::Long:
4491 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004492 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004493 case BuiltinType::LongLong:
4494 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004495 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004496 case BuiltinType::Int128:
4497 case BuiltinType::UInt128:
4498 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004499 }
4500}
4501
Eli Friedman629ffb92009-08-20 04:21:42 +00004502/// \brief Whether this is a promotable bitfield reference according
4503/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4504///
4505/// \returns the type this bit-field will promote to, or NULL if no
4506/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004507QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004508 if (E->isTypeDependent() || E->isValueDependent())
4509 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004510
4511 // FIXME: We should not do this unless E->refersToBitField() is true. This
4512 // matters in C where getSourceBitField() will find bit-fields for various
4513 // cases where the source expression is not a bit-field designator.
4514
John McCalld25db7e2013-05-06 21:39:12 +00004515 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004516 if (!Field)
4517 return QualType();
4518
4519 QualType FT = Field->getType();
4520
Richard Smithcaf33902011-10-10 18:28:20 +00004521 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004522 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004523 // C++ [conv.prom]p5:
4524 // A prvalue for an integral bit-field can be converted to a prvalue of type
4525 // int if int can represent all the values of the bit-field; otherwise, it
4526 // can be converted to unsigned int if unsigned int can represent all the
4527 // values of the bit-field. If the bit-field is larger yet, no integral
4528 // promotion applies to it.
4529 // C11 6.3.1.1/2:
4530 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4531 // If an int can represent all values of the original type (as restricted by
4532 // the width, for a bit-field), the value is converted to an int; otherwise,
4533 // it is converted to an unsigned int.
4534 //
4535 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4536 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004537 if (BitWidth < IntSize)
4538 return IntTy;
4539
4540 if (BitWidth == IntSize)
4541 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4542
4543 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004544 // like the base type. GCC has some weird bugs in this area that we
4545 // deliberately do not follow (GCC follows a pre-standard resolution to
4546 // C's DR315 which treats bit-width as being part of the type, and this leaks
4547 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004548 return QualType();
4549}
4550
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004551/// getPromotedIntegerType - Returns the type that Promotable will
4552/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4553/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004554QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004555 assert(!Promotable.isNull());
4556 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004557 if (const EnumType *ET = Promotable->getAs<EnumType>())
4558 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004559
4560 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4561 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4562 // (3.9.1) can be converted to a prvalue of the first of the following
4563 // types that can represent all the values of its underlying type:
4564 // int, unsigned int, long int, unsigned long int, long long int, or
4565 // unsigned long long int [...]
4566 // FIXME: Is there some better way to compute this?
4567 if (BT->getKind() == BuiltinType::WChar_S ||
4568 BT->getKind() == BuiltinType::WChar_U ||
4569 BT->getKind() == BuiltinType::Char16 ||
4570 BT->getKind() == BuiltinType::Char32) {
4571 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4572 uint64_t FromSize = getTypeSize(BT);
4573 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4574 LongLongTy, UnsignedLongLongTy };
4575 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4576 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4577 if (FromSize < ToSize ||
4578 (FromSize == ToSize &&
4579 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4580 return PromoteTypes[Idx];
4581 }
4582 llvm_unreachable("char type should fit into long long");
4583 }
4584 }
4585
4586 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004587 if (Promotable->isSignedIntegerType())
4588 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004589 uint64_t PromotableSize = getIntWidth(Promotable);
4590 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004591 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4592 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4593}
4594
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004595/// \brief Recurses in pointer/array types until it finds an objc retainable
4596/// type and returns its ownership.
4597Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4598 while (!T.isNull()) {
4599 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4600 return T.getObjCLifetime();
4601 if (T->isArrayType())
4602 T = getBaseElementType(T);
4603 else if (const PointerType *PT = T->getAs<PointerType>())
4604 T = PT->getPointeeType();
4605 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004606 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004607 else
4608 break;
4609 }
4610
4611 return Qualifiers::OCL_None;
4612}
4613
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004614static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4615 // Incomplete enum types are not treated as integer types.
4616 // FIXME: In C++, enum types are never integer types.
4617 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4618 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004619 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004620}
4621
Mike Stump11289f42009-09-09 15:08:12 +00004622/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004623/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004624/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004625int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004626 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4627 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004628
4629 // Unwrap enums to their underlying type.
4630 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4631 LHSC = getIntegerTypeForEnum(ET);
4632 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4633 RHSC = getIntegerTypeForEnum(ET);
4634
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004635 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004636
Chris Lattner76a00cf2008-04-06 22:59:24 +00004637 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4638 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004639
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004640 unsigned LHSRank = getIntegerRank(LHSC);
4641 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004642
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004643 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4644 if (LHSRank == RHSRank) return 0;
4645 return LHSRank > RHSRank ? 1 : -1;
4646 }
Mike Stump11289f42009-09-09 15:08:12 +00004647
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004648 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4649 if (LHSUnsigned) {
4650 // If the unsigned [LHS] type is larger, return it.
4651 if (LHSRank >= RHSRank)
4652 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004653
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004654 // If the signed type can represent all values of the unsigned type, it
4655 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004656 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004657 return -1;
4658 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004659
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004660 // If the unsigned [RHS] type is larger, return it.
4661 if (RHSRank >= LHSRank)
4662 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004663
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004664 // If the signed type can represent all values of the unsigned type, it
4665 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004666 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004667 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004668}
Anders Carlsson98f07902007-08-17 05:31:46 +00004669
Mike Stump11289f42009-09-09 15:08:12 +00004670// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004671QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004672 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004673 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004674 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004675
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004676 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004677
Anders Carlsson98f07902007-08-17 05:31:46 +00004678 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004679 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004680 // int flags;
4681 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004682 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004683 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004684 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004685 FieldTypes[3] = LongTy;
4686
Anders Carlsson98f07902007-08-17 05:31:46 +00004687 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004688 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004689 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004690 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004691 SourceLocation(), nullptr,
4692 FieldTypes[i], /*TInfo=*/nullptr,
4693 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004694 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004695 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004696 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004697 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004698 }
4699
Douglas Gregord5058122010-02-11 01:19:42 +00004700 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004701 }
Mike Stump11289f42009-09-09 15:08:12 +00004702
Anders Carlsson98f07902007-08-17 05:31:46 +00004703 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004704}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004705
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004706QualType ASTContext::getObjCSuperType() const {
4707 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004708 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004709 TUDecl->addDecl(ObjCSuperTypeDecl);
4710 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4711 }
4712 return ObjCSuperType;
4713}
4714
Douglas Gregor512b0772009-04-23 22:29:11 +00004715void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004716 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004717 assert(Rec && "Invalid CFConstantStringType");
4718 CFConstantStringTypeDecl = Rec->getDecl();
4719}
4720
Jay Foad39c79802011-01-12 09:06:06 +00004721QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004722 if (BlockDescriptorType)
4723 return getTagDeclType(BlockDescriptorType);
4724
Alp Toker2dea15b2013-12-17 01:22:38 +00004725 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004726 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004727 RD = buildImplicitRecord("__block_descriptor");
4728 RD->startDefinition();
4729
Mike Stumpd0153282009-10-20 02:12:22 +00004730 QualType FieldTypes[] = {
4731 UnsignedLongTy,
4732 UnsignedLongTy,
4733 };
4734
Craig Topperd6d31ac2013-07-15 08:24:27 +00004735 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004736 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004737 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004738 };
4739
4740 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004741 FieldDecl *Field = FieldDecl::Create(
4742 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004743 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4744 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004745 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004746 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004747 }
4748
Alp Toker2dea15b2013-12-17 01:22:38 +00004749 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004750
Alp Toker2dea15b2013-12-17 01:22:38 +00004751 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004752
4753 return getTagDeclType(BlockDescriptorType);
4754}
4755
Jay Foad39c79802011-01-12 09:06:06 +00004756QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004757 if (BlockDescriptorExtendedType)
4758 return getTagDeclType(BlockDescriptorExtendedType);
4759
Alp Toker2dea15b2013-12-17 01:22:38 +00004760 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004761 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004762 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4763 RD->startDefinition();
4764
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004765 QualType FieldTypes[] = {
4766 UnsignedLongTy,
4767 UnsignedLongTy,
4768 getPointerType(VoidPtrTy),
4769 getPointerType(VoidPtrTy)
4770 };
4771
Craig Topperd6d31ac2013-07-15 08:24:27 +00004772 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004773 "reserved",
4774 "Size",
4775 "CopyFuncPtr",
4776 "DestroyFuncPtr"
4777 };
4778
4779 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004780 FieldDecl *Field = FieldDecl::Create(
4781 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004782 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4783 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004784 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004785 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004786 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004787 }
4788
Alp Toker2dea15b2013-12-17 01:22:38 +00004789 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004790
Alp Toker2dea15b2013-12-17 01:22:38 +00004791 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004792 return getTagDeclType(BlockDescriptorExtendedType);
4793}
4794
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004795/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4796/// requires copy/dispose. Note that this must match the logic
4797/// in buildByrefHelpers.
4798bool ASTContext::BlockRequiresCopying(QualType Ty,
4799 const VarDecl *D) {
4800 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4801 const Expr *copyExpr = getBlockVarCopyInits(D);
4802 if (!copyExpr && record->hasTrivialDestructor()) return false;
4803
Mike Stump94967902009-10-21 18:16:27 +00004804 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004805 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004806
4807 if (!Ty->isObjCRetainableType()) return false;
4808
4809 Qualifiers qs = Ty.getQualifiers();
4810
4811 // If we have lifetime, that dominates.
4812 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4813 assert(getLangOpts().ObjCAutoRefCount);
4814
4815 switch (lifetime) {
4816 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4817
4818 // These are just bits as far as the runtime is concerned.
4819 case Qualifiers::OCL_ExplicitNone:
4820 case Qualifiers::OCL_Autoreleasing:
4821 return false;
4822
4823 // Tell the runtime that this is ARC __weak, called by the
4824 // byref routines.
4825 case Qualifiers::OCL_Weak:
4826 // ARC __strong __block variables need to be retained.
4827 case Qualifiers::OCL_Strong:
4828 return true;
4829 }
4830 llvm_unreachable("fell out of lifetime switch!");
4831 }
4832 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4833 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004834}
4835
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004836bool ASTContext::getByrefLifetime(QualType Ty,
4837 Qualifiers::ObjCLifetime &LifeTime,
4838 bool &HasByrefExtendedLayout) const {
4839
4840 if (!getLangOpts().ObjC1 ||
4841 getLangOpts().getGC() != LangOptions::NonGC)
4842 return false;
4843
4844 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004845 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004846 HasByrefExtendedLayout = true;
4847 LifeTime = Qualifiers::OCL_None;
4848 }
4849 else if (getLangOpts().ObjCAutoRefCount)
4850 LifeTime = Ty.getObjCLifetime();
4851 // MRR.
4852 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4853 LifeTime = Qualifiers::OCL_ExplicitNone;
4854 else
4855 LifeTime = Qualifiers::OCL_None;
4856 return true;
4857}
4858
Douglas Gregorbab8a962011-09-08 01:46:34 +00004859TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4860 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004861 ObjCInstanceTypeDecl =
4862 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004863 return ObjCInstanceTypeDecl;
4864}
4865
Anders Carlsson18acd442007-10-29 06:33:42 +00004866// This returns true if a type has been typedefed to BOOL:
4867// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004868static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004869 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004870 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4871 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004872
Anders Carlssond8499822007-10-29 05:01:08 +00004873 return false;
4874}
4875
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004876/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004877/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004878CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004879 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4880 return CharUnits::Zero();
4881
Ken Dyck40775002010-01-11 17:06:35 +00004882 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004883
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004884 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004885 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004886 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004887 // Treat arrays as pointers, since that's how they're passed in.
4888 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004889 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004890 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004891}
4892
Hans Wennborg56fc62b2014-07-17 20:25:23 +00004893bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4894 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4895 VD->getType()->isIntegralOrEnumerationType() &&
4896 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4897}
4898
Ken Dyck40775002010-01-11 17:06:35 +00004899static inline
4900std::string charUnitsToString(const CharUnits &CU) {
4901 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004902}
4903
John McCall351762c2011-02-07 10:33:21 +00004904/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004905/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004906std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4907 std::string S;
4908
David Chisnall950a9512009-11-17 19:33:30 +00004909 const BlockDecl *Decl = Expr->getBlockDecl();
4910 QualType BlockTy =
4911 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4912 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004913 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004914 getObjCEncodingForMethodParameter(
4915 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4916 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004917 else
Alp Toker314cc812014-01-25 16:55:45 +00004918 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004919 // Compute size of all parameters.
4920 // Start with computing size of a pointer in number of bytes.
4921 // FIXME: There might(should) be a better way of doing this computation!
4922 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004923 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4924 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004925 for (auto PI : Decl->params()) {
4926 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004927 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004928 if (sz.isZero())
4929 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004930 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004931 ParmOffset += sz;
4932 }
4933 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004934 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004935 // Block pointer and offset.
4936 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004937
4938 // Argument types.
4939 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004940 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004941 QualType PType = PVDecl->getOriginalType();
4942 if (const ArrayType *AT =
4943 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4944 // Use array's original type only if it has known number of
4945 // elements.
4946 if (!isa<ConstantArrayType>(AT))
4947 PType = PVDecl->getType();
4948 } else if (PType->isFunctionType())
4949 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004950 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004951 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4952 S, true /*Extended*/);
4953 else
4954 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004955 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004956 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004957 }
John McCall351762c2011-02-07 10:33:21 +00004958
4959 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004960}
4961
Douglas Gregora9d84932011-05-27 01:19:52 +00004962bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004963 std::string& S) {
4964 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004965 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004966 CharUnits ParmOffset;
4967 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004968 for (auto PI : Decl->params()) {
4969 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004970 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004971 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004972 continue;
4973
David Chisnall50e4eba2010-12-30 14:05:53 +00004974 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004975 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004976 ParmOffset += sz;
4977 }
4978 S += charUnitsToString(ParmOffset);
4979 ParmOffset = CharUnits::Zero();
4980
4981 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004982 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004983 QualType PType = PVDecl->getOriginalType();
4984 if (const ArrayType *AT =
4985 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4986 // Use array's original type only if it has known number of
4987 // elements.
4988 if (!isa<ConstantArrayType>(AT))
4989 PType = PVDecl->getType();
4990 } else if (PType->isFunctionType())
4991 PType = PVDecl->getType();
4992 getObjCEncodingForType(PType, S);
4993 S += charUnitsToString(ParmOffset);
4994 ParmOffset += getObjCEncodingTypeSize(PType);
4995 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004996
4997 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004998}
4999
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005000/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5001/// method parameter or return type. If Extended, include class names and
5002/// block object types.
5003void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5004 QualType T, std::string& S,
5005 bool Extended) const {
5006 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5007 getObjCEncodingForTypeQualifier(QT, S);
5008 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005009 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005010 true /*OutermostType*/,
5011 false /*EncodingProperty*/,
5012 false /*StructField*/,
5013 Extended /*EncodeBlockParameters*/,
5014 Extended /*EncodeClassNames*/);
5015}
5016
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005017/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005018/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005019bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005020 std::string& S,
5021 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005022 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005023 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005024 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5025 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005026 // Compute size of all parameters.
5027 // Start with computing size of a pointer in number of bytes.
5028 // FIXME: There might(should) be a better way of doing this computation!
5029 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005030 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005031 // The first two arguments (self and _cmd) are pointers; account for
5032 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005033 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005034 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005035 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005036 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005037 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005038 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005039 continue;
5040
Ken Dyck40775002010-01-11 17:06:35 +00005041 assert (sz.isPositive() &&
5042 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005043 ParmOffset += sz;
5044 }
Ken Dyck40775002010-01-11 17:06:35 +00005045 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005046 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005047 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005048
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005049 // Argument types.
5050 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005051 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005052 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005053 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005054 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005055 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005056 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5057 // Use array's original type only if it has known number of
5058 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005059 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005060 PType = PVDecl->getType();
5061 } else if (PType->isFunctionType())
5062 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005063 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5064 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005065 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005066 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005067 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005068
5069 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005070}
5071
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005072ObjCPropertyImplDecl *
5073ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5074 const ObjCPropertyDecl *PD,
5075 const Decl *Container) const {
5076 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005077 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005078 if (const ObjCCategoryImplDecl *CID =
5079 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005080 for (auto *PID : CID->property_impls())
5081 if (PID->getPropertyDecl() == PD)
5082 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005083 } else {
5084 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5085 for (auto *PID : OID->property_impls())
5086 if (PID->getPropertyDecl() == PD)
5087 return PID;
5088 }
5089 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005090}
5091
Daniel Dunbar4932b362008-08-28 04:38:10 +00005092/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005093/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005094/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5095/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005096/// Property attributes are stored as a comma-delimited C string. The simple
5097/// attributes readonly and bycopy are encoded as single characters. The
5098/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5099/// encoded as single characters, followed by an identifier. Property types
5100/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005101/// these attributes are defined by the following enumeration:
5102/// @code
5103/// enum PropertyAttributes {
5104/// kPropertyReadOnly = 'R', // property is read-only.
5105/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5106/// kPropertyByref = '&', // property is a reference to the value last assigned
5107/// kPropertyDynamic = 'D', // property is dynamic
5108/// kPropertyGetter = 'G', // followed by getter selector name
5109/// kPropertySetter = 'S', // followed by setter selector name
5110/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005111/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005112/// kPropertyWeak = 'W' // 'weak' property
5113/// kPropertyStrong = 'P' // property GC'able
5114/// kPropertyNonAtomic = 'N' // property non-atomic
5115/// };
5116/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005117void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005118 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005119 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005120 // Collect information from the property implementation decl(s).
5121 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005122 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005123
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005124 if (ObjCPropertyImplDecl *PropertyImpDecl =
5125 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5126 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5127 Dynamic = true;
5128 else
5129 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005130 }
5131
5132 // FIXME: This is not very efficient.
5133 S = "T";
5134
5135 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005136 // GCC has some special rules regarding encoding of properties which
5137 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005138 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005139
5140 if (PD->isReadOnly()) {
5141 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005142 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5143 S += ",C";
5144 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5145 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005146 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5147 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005148 } else {
5149 switch (PD->getSetterKind()) {
5150 case ObjCPropertyDecl::Assign: break;
5151 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005152 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005153 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005154 }
5155 }
5156
5157 // It really isn't clear at all what this means, since properties
5158 // are "dynamic by default".
5159 if (Dynamic)
5160 S += ",D";
5161
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005162 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5163 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005164
Daniel Dunbar4932b362008-08-28 04:38:10 +00005165 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5166 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005167 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005168 }
5169
5170 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5171 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005172 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005173 }
5174
5175 if (SynthesizePID) {
5176 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5177 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005178 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005179 }
5180
5181 // FIXME: OBJCGC: weak & strong
5182}
5183
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005184/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005185/// Another legacy compatibility encoding: 32-bit longs are encoded as
5186/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005187/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5188///
5189void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005190 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005191 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005192 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005193 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005194 else
Jay Foad39c79802011-01-12 09:06:06 +00005195 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005196 PointeeTy = IntTy;
5197 }
5198 }
5199}
5200
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005201void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005202 const FieldDecl *Field,
5203 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005204 // We follow the behavior of gcc, expanding structures which are
5205 // directly pointed to, and expanding embedded structures. Note that
5206 // these rules are sufficient to prevent recursive encoding of the
5207 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005208 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005209 true /* outermost type */, false, false,
5210 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005211}
5212
Joe Groff98ac7d22014-07-07 22:25:15 +00005213void ASTContext::getObjCEncodingForPropertyType(QualType T,
5214 std::string& S) const {
5215 // Encode result type.
5216 // GCC has some special rules regarding encoding of properties which
5217 // closely resembles encoding of ivars.
5218 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5219 true /* outermost type */,
5220 true /* encoding property */);
5221}
5222
John McCall393a78d2012-12-20 02:45:14 +00005223static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5224 BuiltinType::Kind kind) {
5225 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005226 case BuiltinType::Void: return 'v';
5227 case BuiltinType::Bool: return 'B';
5228 case BuiltinType::Char_U:
5229 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005230 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005231 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005232 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005233 case BuiltinType::UInt: return 'I';
5234 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005235 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005236 case BuiltinType::UInt128: return 'T';
5237 case BuiltinType::ULongLong: return 'Q';
5238 case BuiltinType::Char_S:
5239 case BuiltinType::SChar: return 'c';
5240 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005241 case BuiltinType::WChar_S:
5242 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005243 case BuiltinType::Int: return 'i';
5244 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005245 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005246 case BuiltinType::LongLong: return 'q';
5247 case BuiltinType::Int128: return 't';
5248 case BuiltinType::Float: return 'f';
5249 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005250 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005251 case BuiltinType::NullPtr: return '*'; // like char*
5252
5253 case BuiltinType::Half:
5254 // FIXME: potentially need @encodes for these!
5255 return ' ';
5256
5257 case BuiltinType::ObjCId:
5258 case BuiltinType::ObjCClass:
5259 case BuiltinType::ObjCSel:
5260 llvm_unreachable("@encoding ObjC primitive type");
5261
5262 // OpenCL and placeholder types don't need @encodings.
5263 case BuiltinType::OCLImage1d:
5264 case BuiltinType::OCLImage1dArray:
5265 case BuiltinType::OCLImage1dBuffer:
5266 case BuiltinType::OCLImage2d:
5267 case BuiltinType::OCLImage2dArray:
5268 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005269 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005270 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005271 case BuiltinType::Dependent:
5272#define BUILTIN_TYPE(KIND, ID)
5273#define PLACEHOLDER_TYPE(KIND, ID) \
5274 case BuiltinType::KIND:
5275#include "clang/AST/BuiltinTypes.def"
5276 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005277 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005278 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005279}
5280
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005281static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5282 EnumDecl *Enum = ET->getDecl();
5283
5284 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5285 if (!Enum->isFixed())
5286 return 'i';
5287
5288 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005289 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5290 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005291}
5292
Jay Foad39c79802011-01-12 09:06:06 +00005293static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005294 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005295 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005296 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005297 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5298 // The GNU runtime requires more information; bitfields are encoded as b,
5299 // then the offset (in bits) of the first element, then the type of the
5300 // bitfield, then the size in bits. For example, in this structure:
5301 //
5302 // struct
5303 // {
5304 // int integer;
5305 // int flags:2;
5306 // };
5307 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5308 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5309 // information is not especially sensible, but we're stuck with it for
5310 // compatibility with GCC, although providing it breaks anything that
5311 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005312 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005313 const RecordDecl *RD = FD->getParent();
5314 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005315 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005316 if (const EnumType *ET = T->getAs<EnumType>())
5317 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005318 else {
5319 const BuiltinType *BT = T->castAs<BuiltinType>();
5320 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5321 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005322 }
Richard Smithcaf33902011-10-10 18:28:20 +00005323 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005324}
5325
Daniel Dunbar07d07852009-10-18 21:17:35 +00005326// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005327void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5328 bool ExpandPointedToStructures,
5329 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005330 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005331 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005332 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005333 bool StructField,
5334 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005335 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005336 bool EncodePointerToObjCTypedef,
5337 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005338 CanQualType CT = getCanonicalType(T);
5339 switch (CT->getTypeClass()) {
5340 case Type::Builtin:
5341 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005342 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005343 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005344 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5345 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5346 else
5347 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005348 return;
Mike Stump11289f42009-09-09 15:08:12 +00005349
John McCall393a78d2012-12-20 02:45:14 +00005350 case Type::Complex: {
5351 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005352 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005353 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005354 return;
5355 }
John McCall393a78d2012-12-20 02:45:14 +00005356
5357 case Type::Atomic: {
5358 const AtomicType *AT = T->castAs<AtomicType>();
5359 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005360 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005361 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005362 }
John McCall393a78d2012-12-20 02:45:14 +00005363
5364 // encoding for pointer or reference types.
5365 case Type::Pointer:
5366 case Type::LValueReference:
5367 case Type::RValueReference: {
5368 QualType PointeeTy;
5369 if (isa<PointerType>(CT)) {
5370 const PointerType *PT = T->castAs<PointerType>();
5371 if (PT->isObjCSelType()) {
5372 S += ':';
5373 return;
5374 }
5375 PointeeTy = PT->getPointeeType();
5376 } else {
5377 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5378 }
5379
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005380 bool isReadOnly = false;
5381 // For historical/compatibility reasons, the read-only qualifier of the
5382 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5383 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005384 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005385 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005386 if (OutermostType && T.isConstQualified()) {
5387 isReadOnly = true;
5388 S += 'r';
5389 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005390 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005391 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005392 while (P->getAs<PointerType>())
5393 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005394 if (P.isConstQualified()) {
5395 isReadOnly = true;
5396 S += 'r';
5397 }
5398 }
5399 if (isReadOnly) {
5400 // Another legacy compatibility encoding. Some ObjC qualifier and type
5401 // combinations need to be rearranged.
5402 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005403 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005404 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005405 }
Mike Stump11289f42009-09-09 15:08:12 +00005406
Anders Carlssond8499822007-10-29 05:01:08 +00005407 if (PointeeTy->isCharType()) {
5408 // char pointer types should be encoded as '*' unless it is a
5409 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005410 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005411 S += '*';
5412 return;
5413 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005414 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005415 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5416 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5417 S += '#';
5418 return;
5419 }
5420 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5421 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5422 S += '@';
5423 return;
5424 }
5425 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005426 }
Anders Carlssond8499822007-10-29 05:01:08 +00005427 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005428 getLegacyIntegralTypeEncoding(PointeeTy);
5429
Mike Stump11289f42009-09-09 15:08:12 +00005430 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005431 nullptr, false, false, false, false, false, false,
5432 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005433 return;
5434 }
John McCall393a78d2012-12-20 02:45:14 +00005435
5436 case Type::ConstantArray:
5437 case Type::IncompleteArray:
5438 case Type::VariableArray: {
5439 const ArrayType *AT = cast<ArrayType>(CT);
5440
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005441 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005442 // Incomplete arrays are encoded as a pointer to the array element.
5443 S += '^';
5444
Mike Stump11289f42009-09-09 15:08:12 +00005445 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005446 false, ExpandStructures, FD);
5447 } else {
5448 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005449
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005450 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5451 S += llvm::utostr(CAT->getSize().getZExtValue());
5452 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005453 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005454 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5455 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005456 S += '0';
5457 }
Mike Stump11289f42009-09-09 15:08:12 +00005458
5459 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005460 false, ExpandStructures, FD,
5461 false, false, false, false, false, false,
5462 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005463 S += ']';
5464 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005465 return;
5466 }
Mike Stump11289f42009-09-09 15:08:12 +00005467
John McCall393a78d2012-12-20 02:45:14 +00005468 case Type::FunctionNoProto:
5469 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005470 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005471 return;
Mike Stump11289f42009-09-09 15:08:12 +00005472
John McCall393a78d2012-12-20 02:45:14 +00005473 case Type::Record: {
5474 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005475 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005476 // Anonymous structures print as '?'
5477 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5478 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005479 if (ClassTemplateSpecializationDecl *Spec
5480 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5481 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005482 llvm::raw_string_ostream OS(S);
5483 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005484 TemplateArgs.data(),
5485 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005486 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005487 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005488 } else {
5489 S += '?';
5490 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005491 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005492 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005493 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005494 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005495 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005496 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005497 if (FD) {
5498 S += '"';
5499 S += Field->getNameAsString();
5500 S += '"';
5501 }
Mike Stump11289f42009-09-09 15:08:12 +00005502
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005503 // Special case bit-fields.
5504 if (Field->isBitField()) {
5505 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005506 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005507 } else {
5508 QualType qt = Field->getType();
5509 getLegacyIntegralTypeEncoding(qt);
5510 getObjCEncodingForTypeImpl(qt, S, false, true,
5511 FD, /*OutermostType*/false,
5512 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005513 /*StructField*/true,
5514 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005515 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005516 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005517 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005518 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005519 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005520 return;
5521 }
Mike Stump11289f42009-09-09 15:08:12 +00005522
John McCall393a78d2012-12-20 02:45:14 +00005523 case Type::BlockPointer: {
5524 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005525 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005526 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005527 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005528
5529 S += '<';
5530 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005531 getObjCEncodingForTypeImpl(
5532 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5533 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005534 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5535 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005536 // Block self
5537 S += "@?";
5538 // Block parameters
5539 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005540 for (const auto &I : FPT->param_types())
5541 getObjCEncodingForTypeImpl(
5542 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5543 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005544 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5545 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005546 }
5547 S += '>';
5548 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005549 return;
5550 }
Mike Stump11289f42009-09-09 15:08:12 +00005551
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005552 case Type::ObjCObject: {
5553 // hack to match legacy encoding of *id and *Class
5554 QualType Ty = getObjCObjectPointerType(CT);
5555 if (Ty->isObjCIdType()) {
5556 S += "{objc_object=}";
5557 return;
5558 }
5559 else if (Ty->isObjCClassType()) {
5560 S += "{objc_class=}";
5561 return;
5562 }
5563 }
5564
John McCall393a78d2012-12-20 02:45:14 +00005565 case Type::ObjCInterface: {
5566 // Ignore protocol qualifiers when mangling at this level.
5567 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005568
John McCall393a78d2012-12-20 02:45:14 +00005569 // The assumption seems to be that this assert will succeed
5570 // because nested levels will have filtered out 'id' and 'Class'.
5571 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005572 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005573 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005574 S += '{';
5575 const IdentifierInfo *II = OI->getIdentifier();
5576 S += II->getName();
5577 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005578 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005579 DeepCollectObjCIvars(OI, true, Ivars);
5580 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005581 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005582 if (Field->isBitField())
5583 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005584 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005585 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5586 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005587 EncodePointerToObjCTypedef,
5588 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005589 }
5590 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005591 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005592 }
Mike Stump11289f42009-09-09 15:08:12 +00005593
John McCall393a78d2012-12-20 02:45:14 +00005594 case Type::ObjCObjectPointer: {
5595 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005596 if (OPT->isObjCIdType()) {
5597 S += '@';
5598 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005599 }
Mike Stump11289f42009-09-09 15:08:12 +00005600
Steve Narofff0c86112009-10-28 22:03:49 +00005601 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5602 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5603 // Since this is a binary compatibility issue, need to consult with runtime
5604 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005605 S += '#';
5606 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005607 }
Mike Stump11289f42009-09-09 15:08:12 +00005608
Chris Lattnere7cabb92009-07-13 00:10:46 +00005609 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005610 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005611 ExpandPointedToStructures,
5612 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005613 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005614 // Note that we do extended encoding of protocol qualifer list
5615 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005616 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005617 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005618 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005619 S += I->getNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005620 S += '>';
5621 }
5622 S += '"';
5623 }
5624 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005625 }
Mike Stump11289f42009-09-09 15:08:12 +00005626
Chris Lattnere7cabb92009-07-13 00:10:46 +00005627 QualType PointeeTy = OPT->getPointeeType();
5628 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005629 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5630 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005631 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005632 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005633 // {...};
5634 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005635 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005636 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005637 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5638 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5639 DeepCollectObjCIvars(OI, true, Ivars);
5640 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5641 if (cast<FieldDecl>(Ivars[i]) == FD) {
5642 S += '{';
5643 S += OI->getIdentifier()->getName();
5644 S += '}';
5645 return;
5646 }
5647 }
5648 }
Mike Stump11289f42009-09-09 15:08:12 +00005649 getObjCEncodingForTypeImpl(PointeeTy, S,
5650 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005651 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005652 false, false, false, false, false,
5653 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005654 return;
5655 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005656
5657 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005658 if (OPT->getInterfaceDecl() &&
5659 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005660 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005661 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Aaron Ballman83731462014-03-17 16:14:00 +00005662 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005663 S += '<';
Aaron Ballman83731462014-03-17 16:14:00 +00005664 S += I->getNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005665 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005666 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005667 S += '"';
5668 }
5669 return;
5670 }
Mike Stump11289f42009-09-09 15:08:12 +00005671
John McCalla9e6e8d2010-05-17 23:56:34 +00005672 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005673 // FIXME: we shoul do better than that. 'M' is available.
5674 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005675 // This matches gcc's encoding, even though technically it is insufficient.
5676 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005677 case Type::Vector:
5678 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005679 // Until we have a coherent encoding of these three types, issue warning.
5680 { if (NotEncodedT)
5681 *NotEncodedT = T;
5682 return;
5683 }
5684
5685 // We could see an undeduced auto type here during error recovery.
5686 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005687 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005688 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005689
Richard Smith27d807c2013-04-30 13:56:41 +00005690
John McCall393a78d2012-12-20 02:45:14 +00005691#define ABSTRACT_TYPE(KIND, BASE)
5692#define TYPE(KIND, BASE)
5693#define DEPENDENT_TYPE(KIND, BASE) \
5694 case Type::KIND:
5695#define NON_CANONICAL_TYPE(KIND, BASE) \
5696 case Type::KIND:
5697#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5698 case Type::KIND:
5699#include "clang/AST/TypeNodes.def"
5700 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005701 }
John McCall393a78d2012-12-20 02:45:14 +00005702 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005703}
5704
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005705void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5706 std::string &S,
5707 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005708 bool includeVBases,
5709 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005710 assert(RDecl && "Expected non-null RecordDecl");
5711 assert(!RDecl->isUnion() && "Should not be called for unions");
5712 if (!RDecl->getDefinition())
5713 return;
5714
5715 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5716 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5717 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5718
5719 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005720 for (const auto &BI : CXXRec->bases()) {
5721 if (!BI.isVirtual()) {
5722 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005723 if (base->isEmpty())
5724 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005725 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005726 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5727 std::make_pair(offs, base));
5728 }
5729 }
5730 }
5731
5732 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005733 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005734 uint64_t offs = layout.getFieldOffset(i);
5735 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005736 std::make_pair(offs, Field));
5737 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005738 }
5739
5740 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005741 for (const auto &BI : CXXRec->vbases()) {
5742 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005743 if (base->isEmpty())
5744 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005745 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005746 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5747 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005748 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5749 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005750 }
5751 }
5752
5753 CharUnits size;
5754 if (CXXRec) {
5755 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5756 } else {
5757 size = layout.getSize();
5758 }
5759
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005760#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005761 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005762#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005763 std::multimap<uint64_t, NamedDecl *>::iterator
5764 CurLayObj = FieldOrBaseOffsets.begin();
5765
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005766 if (CXXRec && CXXRec->isDynamicClass() &&
5767 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005768 if (FD) {
5769 S += "\"_vptr$";
5770 std::string recname = CXXRec->getNameAsString();
5771 if (recname.empty()) recname = "?";
5772 S += recname;
5773 S += '"';
5774 }
5775 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005776#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005777 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005778#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005779 }
5780
5781 if (!RDecl->hasFlexibleArrayMember()) {
5782 // Mark the end of the structure.
5783 uint64_t offs = toBits(size);
5784 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005785 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005786 }
5787
5788 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005789#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005790 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005791 if (CurOffs < CurLayObj->first) {
5792 uint64_t padding = CurLayObj->first - CurOffs;
5793 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5794 // packing/alignment of members is different that normal, in which case
5795 // the encoding will be out-of-sync with the real layout.
5796 // If the runtime switches to just consider the size of types without
5797 // taking into account alignment, we could make padding explicit in the
5798 // encoding (e.g. using arrays of chars). The encoding strings would be
5799 // longer then though.
5800 CurOffs += padding;
5801 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005802#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005803
5804 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005805 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005806 break; // reached end of structure.
5807
5808 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5809 // We expand the bases without their virtual bases since those are going
5810 // in the initial structure. Note that this differs from gcc which
5811 // expands virtual bases each time one is encountered in the hierarchy,
5812 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005813 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5814 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005815 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005816#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005817 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005818#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005819 } else {
5820 FieldDecl *field = cast<FieldDecl>(dcl);
5821 if (FD) {
5822 S += '"';
5823 S += field->getNameAsString();
5824 S += '"';
5825 }
5826
5827 if (field->isBitField()) {
5828 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005829#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005830 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005831#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005832 } else {
5833 QualType qt = field->getType();
5834 getLegacyIntegralTypeEncoding(qt);
5835 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5836 /*OutermostType*/false,
5837 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005838 /*StructField*/true,
5839 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005840#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005841 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005842#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005843 }
5844 }
5845 }
5846}
5847
Mike Stump11289f42009-09-09 15:08:12 +00005848void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005849 std::string& S) const {
5850 if (QT & Decl::OBJC_TQ_In)
5851 S += 'n';
5852 if (QT & Decl::OBJC_TQ_Inout)
5853 S += 'N';
5854 if (QT & Decl::OBJC_TQ_Out)
5855 S += 'o';
5856 if (QT & Decl::OBJC_TQ_Bycopy)
5857 S += 'O';
5858 if (QT & Decl::OBJC_TQ_Byref)
5859 S += 'R';
5860 if (QT & Decl::OBJC_TQ_Oneway)
5861 S += 'V';
5862}
5863
Douglas Gregor3ea72692011-08-12 05:46:01 +00005864TypedefDecl *ASTContext::getObjCIdDecl() const {
5865 if (!ObjCIdDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005866 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
Douglas Gregor3ea72692011-08-12 05:46:01 +00005867 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005868 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005869 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005870 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005871}
5872
Douglas Gregor52e02802011-08-12 06:17:30 +00005873TypedefDecl *ASTContext::getObjCSelDecl() const {
5874 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005875 QualType T = getPointerType(ObjCBuiltinSelTy);
5876 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005877 }
5878 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005879}
5880
Douglas Gregor0a586182011-08-12 05:59:41 +00005881TypedefDecl *ASTContext::getObjCClassDecl() const {
5882 if (!ObjCClassDecl) {
Craig Topper36250ad2014-05-12 05:36:57 +00005883 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
Douglas Gregor0a586182011-08-12 05:59:41 +00005884 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005885 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005886 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005887 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005888}
5889
Douglas Gregord53ae832012-01-17 18:09:05 +00005890ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5891 if (!ObjCProtocolClassDecl) {
5892 ObjCProtocolClassDecl
5893 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5894 SourceLocation(),
5895 &Idents.get("Protocol"),
Craig Topper36250ad2014-05-12 05:36:57 +00005896 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00005897 SourceLocation(), true);
5898 }
5899
5900 return ObjCProtocolClassDecl;
5901}
5902
Meador Inge5d3fb222012-06-16 03:34:49 +00005903//===----------------------------------------------------------------------===//
5904// __builtin_va_list Construction Functions
5905//===----------------------------------------------------------------------===//
5906
5907static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5908 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005909 QualType T = Context->getPointerType(Context->CharTy);
5910 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005911}
5912
5913static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5914 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005915 QualType T = Context->getPointerType(Context->VoidTy);
5916 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005917}
5918
Tim Northover9bb857a2013-01-31 12:13:10 +00005919static TypedefDecl *
5920CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005921 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005922 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005923 if (Context->getLangOpts().CPlusPlus) {
5924 // namespace std { struct __va_list {
5925 NamespaceDecl *NS;
5926 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5927 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00005928 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00005929 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00005930 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00005931 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005932 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005933 }
5934
5935 VaListTagDecl->startDefinition();
5936
5937 const size_t NumFields = 5;
5938 QualType FieldTypes[NumFields];
5939 const char *FieldNames[NumFields];
5940
5941 // void *__stack;
5942 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5943 FieldNames[0] = "__stack";
5944
5945 // void *__gr_top;
5946 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5947 FieldNames[1] = "__gr_top";
5948
5949 // void *__vr_top;
5950 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5951 FieldNames[2] = "__vr_top";
5952
5953 // int __gr_offs;
5954 FieldTypes[3] = Context->IntTy;
5955 FieldNames[3] = "__gr_offs";
5956
5957 // int __vr_offs;
5958 FieldTypes[4] = Context->IntTy;
5959 FieldNames[4] = "__vr_offs";
5960
5961 // Create fields
5962 for (unsigned i = 0; i < NumFields; ++i) {
5963 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5964 VaListTagDecl,
5965 SourceLocation(),
5966 SourceLocation(),
5967 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005968 FieldTypes[i], /*TInfo=*/nullptr,
5969 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00005970 /*Mutable=*/false,
5971 ICIS_NoInit);
5972 Field->setAccess(AS_public);
5973 VaListTagDecl->addDecl(Field);
5974 }
5975 VaListTagDecl->completeDefinition();
5976 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5977 Context->VaListTagTy = VaListTagType;
5978
5979 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005980 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005981}
5982
Meador Inge5d3fb222012-06-16 03:34:49 +00005983static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5984 // typedef struct __va_list_tag {
5985 RecordDecl *VaListTagDecl;
5986
Alp Toker2dea15b2013-12-17 01:22:38 +00005987 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005988 VaListTagDecl->startDefinition();
5989
5990 const size_t NumFields = 5;
5991 QualType FieldTypes[NumFields];
5992 const char *FieldNames[NumFields];
5993
5994 // unsigned char gpr;
5995 FieldTypes[0] = Context->UnsignedCharTy;
5996 FieldNames[0] = "gpr";
5997
5998 // unsigned char fpr;
5999 FieldTypes[1] = Context->UnsignedCharTy;
6000 FieldNames[1] = "fpr";
6001
6002 // unsigned short reserved;
6003 FieldTypes[2] = Context->UnsignedShortTy;
6004 FieldNames[2] = "reserved";
6005
6006 // void* overflow_arg_area;
6007 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6008 FieldNames[3] = "overflow_arg_area";
6009
6010 // void* reg_save_area;
6011 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6012 FieldNames[4] = "reg_save_area";
6013
6014 // Create fields
6015 for (unsigned i = 0; i < NumFields; ++i) {
6016 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6017 SourceLocation(),
6018 SourceLocation(),
6019 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006020 FieldTypes[i], /*TInfo=*/nullptr,
6021 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006022 /*Mutable=*/false,
6023 ICIS_NoInit);
6024 Field->setAccess(AS_public);
6025 VaListTagDecl->addDecl(Field);
6026 }
6027 VaListTagDecl->completeDefinition();
6028 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006029 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006030
6031 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006032 TypedefDecl *VaListTagTypedefDecl =
6033 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6034
Meador Inge5d3fb222012-06-16 03:34:49 +00006035 QualType VaListTagTypedefType =
6036 Context->getTypedefType(VaListTagTypedefDecl);
6037
6038 // typedef __va_list_tag __builtin_va_list[1];
6039 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6040 QualType VaListTagArrayType
6041 = Context->getConstantArrayType(VaListTagTypedefType,
6042 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006043 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006044}
6045
6046static TypedefDecl *
6047CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6048 // typedef struct __va_list_tag {
6049 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006050 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006051 VaListTagDecl->startDefinition();
6052
6053 const size_t NumFields = 4;
6054 QualType FieldTypes[NumFields];
6055 const char *FieldNames[NumFields];
6056
6057 // unsigned gp_offset;
6058 FieldTypes[0] = Context->UnsignedIntTy;
6059 FieldNames[0] = "gp_offset";
6060
6061 // unsigned fp_offset;
6062 FieldTypes[1] = Context->UnsignedIntTy;
6063 FieldNames[1] = "fp_offset";
6064
6065 // void* overflow_arg_area;
6066 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6067 FieldNames[2] = "overflow_arg_area";
6068
6069 // void* reg_save_area;
6070 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6071 FieldNames[3] = "reg_save_area";
6072
6073 // Create fields
6074 for (unsigned i = 0; i < NumFields; ++i) {
6075 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6076 VaListTagDecl,
6077 SourceLocation(),
6078 SourceLocation(),
6079 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006080 FieldTypes[i], /*TInfo=*/nullptr,
6081 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006082 /*Mutable=*/false,
6083 ICIS_NoInit);
6084 Field->setAccess(AS_public);
6085 VaListTagDecl->addDecl(Field);
6086 }
6087 VaListTagDecl->completeDefinition();
6088 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006089 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006090
6091 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006092 TypedefDecl *VaListTagTypedefDecl =
6093 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6094
Meador Inge5d3fb222012-06-16 03:34:49 +00006095 QualType VaListTagTypedefType =
6096 Context->getTypedefType(VaListTagTypedefDecl);
6097
6098 // typedef __va_list_tag __builtin_va_list[1];
6099 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6100 QualType VaListTagArrayType
6101 = Context->getConstantArrayType(VaListTagTypedefType,
6102 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006103 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006104}
6105
6106static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6107 // typedef int __builtin_va_list[4];
6108 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6109 QualType IntArrayType
6110 = Context->getConstantArrayType(Context->IntTy,
6111 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006112 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006113}
6114
Logan Chien57086ce2012-10-10 06:56:20 +00006115static TypedefDecl *
6116CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006117 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006118 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006119 if (Context->getLangOpts().CPlusPlus) {
6120 // namespace std { struct __va_list {
6121 NamespaceDecl *NS;
6122 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6123 Context->getTranslationUnitDecl(),
6124 /*Inline*/false, SourceLocation(),
6125 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006126 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006127 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006128 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006129 }
6130
6131 VaListDecl->startDefinition();
6132
6133 // void * __ap;
6134 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6135 VaListDecl,
6136 SourceLocation(),
6137 SourceLocation(),
6138 &Context->Idents.get("__ap"),
6139 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006140 /*TInfo=*/nullptr,
6141 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006142 /*Mutable=*/false,
6143 ICIS_NoInit);
6144 Field->setAccess(AS_public);
6145 VaListDecl->addDecl(Field);
6146
6147 // };
6148 VaListDecl->completeDefinition();
6149
6150 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006151 QualType T = Context->getRecordType(VaListDecl);
6152 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006153}
6154
Ulrich Weigand47445072013-05-06 16:26:41 +00006155static TypedefDecl *
6156CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6157 // typedef struct __va_list_tag {
6158 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006159 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006160 VaListTagDecl->startDefinition();
6161
6162 const size_t NumFields = 4;
6163 QualType FieldTypes[NumFields];
6164 const char *FieldNames[NumFields];
6165
6166 // long __gpr;
6167 FieldTypes[0] = Context->LongTy;
6168 FieldNames[0] = "__gpr";
6169
6170 // long __fpr;
6171 FieldTypes[1] = Context->LongTy;
6172 FieldNames[1] = "__fpr";
6173
6174 // void *__overflow_arg_area;
6175 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6176 FieldNames[2] = "__overflow_arg_area";
6177
6178 // void *__reg_save_area;
6179 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6180 FieldNames[3] = "__reg_save_area";
6181
6182 // Create fields
6183 for (unsigned i = 0; i < NumFields; ++i) {
6184 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6185 VaListTagDecl,
6186 SourceLocation(),
6187 SourceLocation(),
6188 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006189 FieldTypes[i], /*TInfo=*/nullptr,
6190 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006191 /*Mutable=*/false,
6192 ICIS_NoInit);
6193 Field->setAccess(AS_public);
6194 VaListTagDecl->addDecl(Field);
6195 }
6196 VaListTagDecl->completeDefinition();
6197 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6198 Context->VaListTagTy = VaListTagType;
6199
6200 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006201 TypedefDecl *VaListTagTypedefDecl =
6202 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006203 QualType VaListTagTypedefType =
6204 Context->getTypedefType(VaListTagTypedefDecl);
6205
6206 // typedef __va_list_tag __builtin_va_list[1];
6207 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6208 QualType VaListTagArrayType
6209 = Context->getConstantArrayType(VaListTagTypedefType,
6210 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006211
Alp Toker56b5cc92013-12-15 10:36:26 +00006212 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006213}
6214
Meador Inge5d3fb222012-06-16 03:34:49 +00006215static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6216 TargetInfo::BuiltinVaListKind Kind) {
6217 switch (Kind) {
6218 case TargetInfo::CharPtrBuiltinVaList:
6219 return CreateCharPtrBuiltinVaListDecl(Context);
6220 case TargetInfo::VoidPtrBuiltinVaList:
6221 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006222 case TargetInfo::AArch64ABIBuiltinVaList:
6223 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006224 case TargetInfo::PowerABIBuiltinVaList:
6225 return CreatePowerABIBuiltinVaListDecl(Context);
6226 case TargetInfo::X86_64ABIBuiltinVaList:
6227 return CreateX86_64ABIBuiltinVaListDecl(Context);
6228 case TargetInfo::PNaClABIBuiltinVaList:
6229 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006230 case TargetInfo::AAPCSABIBuiltinVaList:
6231 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006232 case TargetInfo::SystemZBuiltinVaList:
6233 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006234 }
6235
6236 llvm_unreachable("Unhandled __builtin_va_list type kind");
6237}
6238
6239TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006240 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006241 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006242 assert(BuiltinVaListDecl->isImplicit());
6243 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006244
6245 return BuiltinVaListDecl;
6246}
6247
Meador Ingecfb60902012-07-01 15:57:25 +00006248QualType ASTContext::getVaListTagType() const {
6249 // Force the creation of VaListTagTy by building the __builtin_va_list
6250 // declaration.
6251 if (VaListTagTy.isNull())
6252 (void) getBuiltinVaListDecl();
6253
6254 return VaListTagTy;
6255}
6256
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006257void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006258 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006259 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006260
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006261 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006262}
6263
John McCalld28ae272009-12-02 08:04:21 +00006264/// \brief Retrieve the template name that corresponds to a non-empty
6265/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006266TemplateName
6267ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6268 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006269 unsigned size = End - Begin;
6270 assert(size > 1 && "set is not overloaded!");
6271
6272 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6273 size * sizeof(FunctionTemplateDecl*));
6274 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6275
6276 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006277 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006278 NamedDecl *D = *I;
6279 assert(isa<FunctionTemplateDecl>(D) ||
6280 (isa<UsingShadowDecl>(D) &&
6281 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6282 *Storage++ = D;
6283 }
6284
6285 return TemplateName(OT);
6286}
6287
Douglas Gregordc572a32009-03-30 22:58:21 +00006288/// \brief Retrieve the template name that represents a qualified
6289/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006290TemplateName
6291ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6292 bool TemplateKeyword,
6293 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006294 assert(NNS && "Missing nested-name-specifier in qualified template name");
6295
Douglas Gregorc42075a2010-02-04 18:10:26 +00006296 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006297 llvm::FoldingSetNodeID ID;
6298 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6299
Craig Topper36250ad2014-05-12 05:36:57 +00006300 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006301 QualifiedTemplateName *QTN =
6302 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6303 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006304 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6305 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006306 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6307 }
6308
6309 return TemplateName(QTN);
6310}
6311
6312/// \brief Retrieve the template name that represents a dependent
6313/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006314TemplateName
6315ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6316 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006317 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006318 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006319
6320 llvm::FoldingSetNodeID ID;
6321 DependentTemplateName::Profile(ID, NNS, Name);
6322
Craig Topper36250ad2014-05-12 05:36:57 +00006323 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006324 DependentTemplateName *QTN =
6325 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6326
6327 if (QTN)
6328 return TemplateName(QTN);
6329
6330 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6331 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006332 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6333 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006334 } else {
6335 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006336 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6337 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006338 DependentTemplateName *CheckQTN =
6339 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6340 assert(!CheckQTN && "Dependent type name canonicalization broken");
6341 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006342 }
6343
6344 DependentTemplateNames.InsertNode(QTN, InsertPos);
6345 return TemplateName(QTN);
6346}
6347
Douglas Gregor71395fa2009-11-04 00:56:37 +00006348/// \brief Retrieve the template name that represents a dependent
6349/// template name such as \c MetaFun::template operator+.
6350TemplateName
6351ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006352 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006353 assert((!NNS || NNS->isDependent()) &&
6354 "Nested name specifier must be dependent");
6355
6356 llvm::FoldingSetNodeID ID;
6357 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006358
6359 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006360 DependentTemplateName *QTN
6361 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006362
6363 if (QTN)
6364 return TemplateName(QTN);
6365
6366 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6367 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006368 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6369 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006370 } else {
6371 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006372 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6373 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006374
6375 DependentTemplateName *CheckQTN
6376 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6377 assert(!CheckQTN && "Dependent template name canonicalization broken");
6378 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006379 }
6380
6381 DependentTemplateNames.InsertNode(QTN, InsertPos);
6382 return TemplateName(QTN);
6383}
6384
Douglas Gregor5590be02011-01-15 06:45:20 +00006385TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006386ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6387 TemplateName replacement) const {
6388 llvm::FoldingSetNodeID ID;
6389 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006390
6391 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006392 SubstTemplateTemplateParmStorage *subst
6393 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6394
6395 if (!subst) {
6396 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6397 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6398 }
6399
6400 return TemplateName(subst);
6401}
6402
6403TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006404ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6405 const TemplateArgument &ArgPack) const {
6406 ASTContext &Self = const_cast<ASTContext &>(*this);
6407 llvm::FoldingSetNodeID ID;
6408 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006409
6410 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006411 SubstTemplateTemplateParmPackStorage *Subst
6412 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6413
6414 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006415 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006416 ArgPack.pack_size(),
6417 ArgPack.pack_begin());
6418 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6419 }
6420
6421 return TemplateName(Subst);
6422}
6423
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006424/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006425/// TargetInfo, produce the corresponding type. The unsigned @p Type
6426/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006427CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006428 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006429 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006430 case TargetInfo::SignedChar: return SignedCharTy;
6431 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006432 case TargetInfo::SignedShort: return ShortTy;
6433 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6434 case TargetInfo::SignedInt: return IntTy;
6435 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6436 case TargetInfo::SignedLong: return LongTy;
6437 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6438 case TargetInfo::SignedLongLong: return LongLongTy;
6439 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6440 }
6441
David Blaikie83d382b2011-09-23 05:06:16 +00006442 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006443}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006444
6445//===----------------------------------------------------------------------===//
6446// Type Predicates.
6447//===----------------------------------------------------------------------===//
6448
Fariborz Jahanian96207692009-02-18 21:49:28 +00006449/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6450/// garbage collection attribute.
6451///
John McCall553d45a2011-01-12 00:34:59 +00006452Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006453 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006454 return Qualifiers::GCNone;
6455
David Blaikiebbafb8a2012-03-11 07:00:24 +00006456 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006457 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6458
6459 // Default behaviour under objective-C's gc is for ObjC pointers
6460 // (or pointers to them) be treated as though they were declared
6461 // as __strong.
6462 if (GCAttrs == Qualifiers::GCNone) {
6463 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6464 return Qualifiers::Strong;
6465 else if (Ty->isPointerType())
6466 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6467 } else {
6468 // It's not valid to set GC attributes on anything that isn't a
6469 // pointer.
6470#ifndef NDEBUG
6471 QualType CT = Ty->getCanonicalTypeInternal();
6472 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6473 CT = AT->getElementType();
6474 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6475#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006476 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006477 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006478}
6479
Chris Lattner49af6a42008-04-07 06:51:04 +00006480//===----------------------------------------------------------------------===//
6481// Type Compatibility Testing
6482//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006483
Mike Stump11289f42009-09-09 15:08:12 +00006484/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006485/// compatible.
6486static bool areCompatVectorTypes(const VectorType *LHS,
6487 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006488 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006489 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006490 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006491}
6492
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006493bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6494 QualType SecondVec) {
6495 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6496 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6497
6498 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6499 return true;
6500
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006501 // Treat Neon vector types and most AltiVec vector types as if they are the
6502 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006503 const VectorType *First = FirstVec->getAs<VectorType>();
6504 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006505 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006506 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006507 First->getVectorKind() != VectorType::AltiVecPixel &&
6508 First->getVectorKind() != VectorType::AltiVecBool &&
6509 Second->getVectorKind() != VectorType::AltiVecPixel &&
6510 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006511 return true;
6512
6513 return false;
6514}
6515
Steve Naroff8e6aee52009-07-23 01:01:38 +00006516//===----------------------------------------------------------------------===//
6517// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6518//===----------------------------------------------------------------------===//
6519
6520/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6521/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006522bool
6523ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6524 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006525 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006526 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006527 for (auto *PI : rProto->protocols())
6528 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006529 return true;
6530 return false;
6531}
6532
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006533/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6534/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006535bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6536 QualType rhs) {
6537 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6538 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6539 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6540
Aaron Ballman83731462014-03-17 16:14:00 +00006541 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006542 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006543 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006544 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6545 match = true;
6546 break;
6547 }
6548 }
6549 if (!match)
6550 return false;
6551 }
6552 return true;
6553}
6554
Steve Naroff8e6aee52009-07-23 01:01:38 +00006555/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6556/// ObjCQualifiedIDType.
6557bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6558 bool compare) {
6559 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006560 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006561 lhs->isObjCIdType() || lhs->isObjCClassType())
6562 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006563 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006564 rhs->isObjCIdType() || rhs->isObjCClassType())
6565 return true;
6566
6567 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006568 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006569
Steve Naroff8e6aee52009-07-23 01:01:38 +00006570 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006571
Steve Naroff8e6aee52009-07-23 01:01:38 +00006572 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006573 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006574 // make sure we check the class hierarchy.
6575 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006576 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006577 // when comparing an id<P> on lhs with a static type on rhs,
6578 // see if static class implements all of id's protocols, directly or
6579 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006580 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006581 return false;
6582 }
6583 }
6584 // If there are no qualifiers and no interface, we have an 'id'.
6585 return true;
6586 }
Mike Stump11289f42009-09-09 15:08:12 +00006587 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006588 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006589 bool match = false;
6590
6591 // when comparing an id<P> on lhs with a static type on rhs,
6592 // see if static class implements all of id's protocols, directly or
6593 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006594 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006595 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6596 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6597 match = true;
6598 break;
6599 }
6600 }
Mike Stump11289f42009-09-09 15:08:12 +00006601 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006602 // make sure we check the class hierarchy.
6603 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006604 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006605 // when comparing an id<P> on lhs with a static type on rhs,
6606 // see if static class implements all of id's protocols, directly or
6607 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006608 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006609 match = true;
6610 break;
6611 }
6612 }
6613 }
6614 if (!match)
6615 return false;
6616 }
Mike Stump11289f42009-09-09 15:08:12 +00006617
Steve Naroff8e6aee52009-07-23 01:01:38 +00006618 return true;
6619 }
Mike Stump11289f42009-09-09 15:08:12 +00006620
Steve Naroff8e6aee52009-07-23 01:01:38 +00006621 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6622 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6623
Mike Stump11289f42009-09-09 15:08:12 +00006624 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006625 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006626 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006627 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006628 bool match = false;
6629
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006630 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006631 // see if static class implements all of id's protocols, directly or
6632 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006633 // First, lhs protocols in the qualifier list must be found, direct
6634 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006635 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006636 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6637 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6638 match = true;
6639 break;
6640 }
6641 }
6642 if (!match)
6643 return false;
6644 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006645
6646 // Static class's protocols, or its super class or category protocols
6647 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6648 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6649 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6650 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6651 // This is rather dubious but matches gcc's behavior. If lhs has
6652 // no type qualifier and its class has no static protocol(s)
6653 // assume that it is mismatch.
6654 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6655 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006656 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006657 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006658 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006659 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6660 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6661 match = true;
6662 break;
6663 }
6664 }
6665 if (!match)
6666 return false;
6667 }
6668 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006669 return true;
6670 }
6671 return false;
6672}
6673
Eli Friedman47f77112008-08-22 00:56:42 +00006674/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006675/// compatible for assignment from RHS to LHS. This handles validation of any
6676/// protocol qualifiers on the LHS or RHS.
6677///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006678bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6679 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006680 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6681 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6682
Steve Naroff1329fa02009-07-15 18:40:39 +00006683 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006684 if (LHS->isObjCUnqualifiedIdOrClass() ||
6685 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006686 return true;
6687
John McCall8b07ec22010-05-15 11:32:37 +00006688 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006689 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6690 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006691 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006692
6693 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6694 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6695 QualType(RHSOPT,0));
6696
John McCall8b07ec22010-05-15 11:32:37 +00006697 // If we have 2 user-defined types, fall into that path.
6698 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006699 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006700
Steve Naroff8e6aee52009-07-23 01:01:38 +00006701 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006702}
6703
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006704/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006705/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006706/// arguments in block literals. When passed as arguments, passing 'A*' where
6707/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6708/// not OK. For the return type, the opposite is not OK.
6709bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6710 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006711 const ObjCObjectPointerType *RHSOPT,
6712 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006713 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006714 return true;
6715
6716 if (LHSOPT->isObjCBuiltinType()) {
6717 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6718 }
6719
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006720 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006721 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6722 QualType(RHSOPT,0),
6723 false);
6724
6725 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6726 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6727 if (LHS && RHS) { // We have 2 user-defined types.
6728 if (LHS != RHS) {
6729 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006730 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006731 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006732 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006733 }
6734 else
6735 return true;
6736 }
6737 return false;
6738}
6739
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006740/// getIntersectionOfProtocols - This routine finds the intersection of set
6741/// of protocols inherited from two distinct objective-c pointer objects.
6742/// It is used to build composite qualifier list of the composite type of
6743/// the conditional expression involving two objective-c pointer objects.
6744static
6745void getIntersectionOfProtocols(ASTContext &Context,
6746 const ObjCObjectPointerType *LHSOPT,
6747 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006748 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006749
John McCall8b07ec22010-05-15 11:32:37 +00006750 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6751 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6752 assert(LHS->getInterface() && "LHS must have an interface base");
6753 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006754
6755 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6756 unsigned LHSNumProtocols = LHS->getNumProtocols();
6757 if (LHSNumProtocols > 0)
6758 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6759 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006760 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006761 Context.CollectInheritedProtocols(LHS->getInterface(),
6762 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006763 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6764 LHSInheritedProtocols.end());
6765 }
6766
6767 unsigned RHSNumProtocols = RHS->getNumProtocols();
6768 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006769 ObjCProtocolDecl **RHSProtocols =
6770 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006771 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6772 if (InheritedProtocolSet.count(RHSProtocols[i]))
6773 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006774 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006775 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006776 Context.CollectInheritedProtocols(RHS->getInterface(),
6777 RHSInheritedProtocols);
Craig Topperc6914d02014-08-25 04:15:02 +00006778 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6779 if (InheritedProtocolSet.count(ProtDecl))
6780 IntersectionOfProtocols.push_back(ProtDecl);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006781 }
6782}
6783
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006784/// areCommonBaseCompatible - Returns common base class of the two classes if
6785/// one found. Note that this is O'2 algorithm. But it will be called as the
6786/// last type comparison in a ?-exp of ObjC pointer types before a
6787/// warning is issued. So, its invokation is extremely rare.
6788QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006789 const ObjCObjectPointerType *Lptr,
6790 const ObjCObjectPointerType *Rptr) {
6791 const ObjCObjectType *LHS = Lptr->getObjectType();
6792 const ObjCObjectType *RHS = Rptr->getObjectType();
6793 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6794 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006795 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006796 return QualType();
6797
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006798 do {
John McCall8b07ec22010-05-15 11:32:37 +00006799 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006800 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006801 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006802 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6803
6804 QualType Result = QualType(LHS, 0);
6805 if (!Protocols.empty())
6806 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6807 Result = getObjCObjectPointerType(Result);
6808 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006809 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006810 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006811
6812 return QualType();
6813}
6814
John McCall8b07ec22010-05-15 11:32:37 +00006815bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6816 const ObjCObjectType *RHS) {
6817 assert(LHS->getInterface() && "LHS is not an interface type");
6818 assert(RHS->getInterface() && "RHS is not an interface type");
6819
Chris Lattner49af6a42008-04-07 06:51:04 +00006820 // Verify that the base decls are compatible: the RHS must be a subclass of
6821 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006822 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006823 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006824
Chris Lattner49af6a42008-04-07 06:51:04 +00006825 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6826 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006827 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006828 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006829
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006830 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6831 // More detailed analysis is required.
6832 // OK, if LHS is same or a superclass of RHS *and*
6833 // this LHS, or as RHS's super class is assignment compatible with LHS.
6834 bool IsSuperClass =
6835 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6836 if (IsSuperClass) {
6837 // OK if conversion of LHS to SuperClass results in narrowing of types
6838 // ; i.e., SuperClass may implement at least one of the protocols
6839 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6840 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6841 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6842 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6843 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6844 // qualifiers.
6845 for (auto *RHSPI : RHS->quals())
6846 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6847 // If there is no protocols associated with RHS, it is not a match.
6848 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00006849 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006850
6851 for (const auto *LHSProto : LHS->quals()) {
6852 bool SuperImplementsProtocol = false;
6853 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6854 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6855 SuperImplementsProtocol = true;
6856 break;
6857 }
6858 if (!SuperImplementsProtocol)
6859 return false;
6860 }
6861 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006862 }
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00006863 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006864}
6865
Steve Naroffb7605152009-02-12 17:52:19 +00006866bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6867 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006868 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6869 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006870
Steve Naroff7cae42b2009-07-10 23:34:53 +00006871 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006872 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006873
6874 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6875 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006876}
6877
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006878bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6879 return canAssignObjCInterfaces(
6880 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6881 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6882}
6883
Mike Stump11289f42009-09-09 15:08:12 +00006884/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006885/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006886/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006887/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006888bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6889 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006890 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006891 return hasSameType(LHS, RHS);
6892
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006893 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006894}
6895
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006896bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006897 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006898}
6899
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006900bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6901 return !mergeTypes(LHS, RHS, true).isNull();
6902}
6903
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006904/// mergeTransparentUnionType - if T is a transparent union type and a member
6905/// of T is compatible with SubType, return the merged type, else return
6906/// QualType()
6907QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6908 bool OfBlockPointer,
6909 bool Unqualified) {
6910 if (const RecordType *UT = T->getAsUnionType()) {
6911 RecordDecl *UD = UT->getDecl();
6912 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006913 for (const auto *I : UD->fields()) {
6914 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006915 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6916 if (!MT.isNull())
6917 return MT;
6918 }
6919 }
6920 }
6921
6922 return QualType();
6923}
6924
Alp Toker9cacbab2014-01-20 20:26:09 +00006925/// mergeFunctionParameterTypes - merge two types which appear as function
6926/// parameter types
6927QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6928 bool OfBlockPointer,
6929 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006930 // GNU extension: two types are compatible if they appear as a function
6931 // argument, one of the types is a transparent union type and the other
6932 // type is compatible with a union member
6933 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6934 Unqualified);
6935 if (!lmerge.isNull())
6936 return lmerge;
6937
6938 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6939 Unqualified);
6940 if (!rmerge.isNull())
6941 return rmerge;
6942
6943 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6944}
6945
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006946QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006947 bool OfBlockPointer,
6948 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006949 const FunctionType *lbase = lhs->getAs<FunctionType>();
6950 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006951 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6952 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006953 bool allLTypes = true;
6954 bool allRTypes = true;
6955
6956 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006957 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006958 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006959 QualType RHS = rbase->getReturnType();
6960 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006961 bool UnqualifiedResult = Unqualified;
6962 if (!UnqualifiedResult)
6963 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006964 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006965 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006966 else
Alp Toker314cc812014-01-25 16:55:45 +00006967 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006968 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006969 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006970
6971 if (Unqualified)
6972 retType = retType.getUnqualifiedType();
6973
Alp Toker314cc812014-01-25 16:55:45 +00006974 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6975 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006976 if (Unqualified) {
6977 LRetType = LRetType.getUnqualifiedType();
6978 RRetType = RRetType.getUnqualifiedType();
6979 }
6980
6981 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006982 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006983 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006984 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006985
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006986 // FIXME: double check this
6987 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6988 // rbase->getRegParmAttr() != 0 &&
6989 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006990 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6991 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006992
Douglas Gregor8c940862010-01-18 17:14:39 +00006993 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006994 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006995 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006996
John McCall8c6b56f2010-12-15 01:06:38 +00006997 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006998 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6999 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007000 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7001 return QualType();
7002
John McCall31168b02011-06-15 23:02:42 +00007003 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7004 return QualType();
7005
John McCall8c6b56f2010-12-15 01:06:38 +00007006 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7007 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007008
Rafael Espindola8778c282012-11-29 16:09:03 +00007009 if (lbaseInfo.getNoReturn() != NoReturn)
7010 allLTypes = false;
7011 if (rbaseInfo.getNoReturn() != NoReturn)
7012 allRTypes = false;
7013
John McCall31168b02011-06-15 23:02:42 +00007014 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007015
Eli Friedman47f77112008-08-22 00:56:42 +00007016 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007017 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7018 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007019 // Compatible functions must have the same number of parameters
7020 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007021 return QualType();
7022
7023 // Variadic and non-variadic functions aren't compatible
7024 if (lproto->isVariadic() != rproto->isVariadic())
7025 return QualType();
7026
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007027 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7028 return QualType();
7029
Fariborz Jahanian97676972011-09-28 21:52:05 +00007030 if (LangOpts.ObjCAutoRefCount &&
7031 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7032 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007033
7034 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007035 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007036 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7037 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7038 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7039 QualType paramType = mergeFunctionParameterTypes(
7040 lParamType, rParamType, OfBlockPointer, Unqualified);
7041 if (paramType.isNull())
7042 return QualType();
7043
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007044 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007045 paramType = paramType.getUnqualifiedType();
7046
7047 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007048 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007049 lParamType = lParamType.getUnqualifiedType();
7050 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007051 }
Alp Toker601b22c2014-01-21 23:35:24 +00007052
7053 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007054 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007055 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007056 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007057 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007058
Eli Friedman47f77112008-08-22 00:56:42 +00007059 if (allLTypes) return lhs;
7060 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007061
7062 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7063 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007064 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007065 }
7066
7067 if (lproto) allRTypes = false;
7068 if (rproto) allLTypes = false;
7069
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007070 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007071 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007072 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007073 if (proto->isVariadic()) return QualType();
7074 // Check that the types are compatible with the types that
7075 // would result from default argument promotions (C99 6.7.5.3p15).
7076 // The only types actually affected are promotable integer
7077 // types and floats, which would be passed as a different
7078 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007079 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7080 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007081
Eli Friedman448ce402012-08-30 00:44:15 +00007082 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007083 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007084 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7085 paramTy = Enum->getDecl()->getIntegerType();
7086 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007087 return QualType();
7088 }
Alp Toker601b22c2014-01-21 23:35:24 +00007089
7090 if (paramTy->isPromotableIntegerType() ||
7091 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007092 return QualType();
7093 }
7094
7095 if (allLTypes) return lhs;
7096 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007097
7098 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7099 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007100 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007101 }
7102
7103 if (allLTypes) return lhs;
7104 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007105 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007106}
7107
John McCall433c2e62013-03-21 00:10:07 +00007108/// Given that we have an enum type and a non-enum type, try to merge them.
7109static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7110 QualType other, bool isBlockReturnType) {
7111 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7112 // a signed integer type, or an unsigned integer type.
7113 // Compatibility is based on the underlying type, not the promotion
7114 // type.
7115 QualType underlyingType = ET->getDecl()->getIntegerType();
7116 if (underlyingType.isNull()) return QualType();
7117 if (Context.hasSameType(underlyingType, other))
7118 return other;
7119
7120 // In block return types, we're more permissive and accept any
7121 // integral type of the same size.
7122 if (isBlockReturnType && other->isIntegerType() &&
7123 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7124 return other;
7125
7126 return QualType();
7127}
7128
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007129QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007130 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007131 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007132 // C++ [expr]: If an expression initially has the type "reference to T", the
7133 // type is adjusted to "T" prior to any further analysis, the expression
7134 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007135 // expression is an lvalue unless the reference is an rvalue reference and
7136 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007137 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7138 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007139
7140 if (Unqualified) {
7141 LHS = LHS.getUnqualifiedType();
7142 RHS = RHS.getUnqualifiedType();
7143 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007144
Eli Friedman47f77112008-08-22 00:56:42 +00007145 QualType LHSCan = getCanonicalType(LHS),
7146 RHSCan = getCanonicalType(RHS);
7147
7148 // If two types are identical, they are compatible.
7149 if (LHSCan == RHSCan)
7150 return LHS;
7151
John McCall8ccfcb52009-09-24 19:53:00 +00007152 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007153 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7154 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007155 if (LQuals != RQuals) {
7156 // If any of these qualifiers are different, we have a type
7157 // mismatch.
7158 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007159 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7160 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007161 return QualType();
7162
7163 // Exactly one GC qualifier difference is allowed: __strong is
7164 // okay if the other type has no GC qualifier but is an Objective
7165 // C object pointer (i.e. implicitly strong by default). We fix
7166 // this by pretending that the unqualified type was actually
7167 // qualified __strong.
7168 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7169 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7170 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7171
7172 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7173 return QualType();
7174
7175 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7176 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7177 }
7178 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7179 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7180 }
Eli Friedman47f77112008-08-22 00:56:42 +00007181 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007182 }
7183
7184 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007185
Eli Friedmandcca6332009-06-01 01:22:52 +00007186 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7187 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007188
Chris Lattnerfd652912008-01-14 05:45:46 +00007189 // We want to consider the two function types to be the same for these
7190 // comparisons, just force one to the other.
7191 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7192 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007193
7194 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007195 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7196 LHSClass = Type::ConstantArray;
7197 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7198 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007199
John McCall8b07ec22010-05-15 11:32:37 +00007200 // ObjCInterfaces are just specialized ObjCObjects.
7201 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7202 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7203
Nate Begemance4d7fc2008-04-18 23:10:10 +00007204 // Canonicalize ExtVector -> Vector.
7205 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7206 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007207
Chris Lattner95554662008-04-07 05:43:21 +00007208 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007209 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007210 // Note that we only have special rules for turning block enum
7211 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007212 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007213 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007214 }
John McCall9dd450b2009-09-21 23:43:11 +00007215 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007216 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007217 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007218 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007219 if (OfBlockPointer && !BlockReturnType) {
7220 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7221 return LHS;
7222 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7223 return RHS;
7224 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007225
Eli Friedman47f77112008-08-22 00:56:42 +00007226 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007227 }
Eli Friedman47f77112008-08-22 00:56:42 +00007228
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007229 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007230 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007231#define TYPE(Class, Base)
7232#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007233#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007234#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7235#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7236#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007237 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007238
Richard Smith27d807c2013-04-30 13:56:41 +00007239 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007240 case Type::LValueReference:
7241 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007242 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007243 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007244
John McCall8b07ec22010-05-15 11:32:37 +00007245 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007246 case Type::IncompleteArray:
7247 case Type::VariableArray:
7248 case Type::FunctionProto:
7249 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007250 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007251
Chris Lattnerfd652912008-01-14 05:45:46 +00007252 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007253 {
7254 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007255 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7256 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007257 if (Unqualified) {
7258 LHSPointee = LHSPointee.getUnqualifiedType();
7259 RHSPointee = RHSPointee.getUnqualifiedType();
7260 }
7261 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7262 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007263 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007264 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007265 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007266 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007267 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007268 return getPointerType(ResultType);
7269 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007270 case Type::BlockPointer:
7271 {
7272 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007273 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7274 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007275 if (Unqualified) {
7276 LHSPointee = LHSPointee.getUnqualifiedType();
7277 RHSPointee = RHSPointee.getUnqualifiedType();
7278 }
7279 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7280 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007281 if (ResultType.isNull()) return QualType();
7282 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7283 return LHS;
7284 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7285 return RHS;
7286 return getBlockPointerType(ResultType);
7287 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007288 case Type::Atomic:
7289 {
7290 // Merge two pointer types, while trying to preserve typedef info
7291 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7292 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7293 if (Unqualified) {
7294 LHSValue = LHSValue.getUnqualifiedType();
7295 RHSValue = RHSValue.getUnqualifiedType();
7296 }
7297 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7298 Unqualified);
7299 if (ResultType.isNull()) return QualType();
7300 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7301 return LHS;
7302 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7303 return RHS;
7304 return getAtomicType(ResultType);
7305 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007306 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007307 {
7308 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7309 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7310 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7311 return QualType();
7312
7313 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7314 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007315 if (Unqualified) {
7316 LHSElem = LHSElem.getUnqualifiedType();
7317 RHSElem = RHSElem.getUnqualifiedType();
7318 }
7319
7320 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007321 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007322 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7323 return LHS;
7324 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7325 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007326 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7327 ArrayType::ArraySizeModifier(), 0);
7328 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7329 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007330 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7331 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007332 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7333 return LHS;
7334 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7335 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007336 if (LVAT) {
7337 // FIXME: This isn't correct! But tricky to implement because
7338 // the array's size has to be the size of LHS, but the type
7339 // has to be different.
7340 return LHS;
7341 }
7342 if (RVAT) {
7343 // FIXME: This isn't correct! But tricky to implement because
7344 // the array's size has to be the size of RHS, but the type
7345 // has to be different.
7346 return RHS;
7347 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007348 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7349 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007350 return getIncompleteArrayType(ResultType,
7351 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007352 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007353 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007354 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007355 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007356 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007357 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007358 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007359 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007360 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007361 case Type::Complex:
7362 // Distinct complex types are incompatible.
7363 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007364 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007365 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007366 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7367 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007368 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007369 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007370 case Type::ObjCObject: {
7371 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007372 // FIXME: This should be type compatibility, e.g. whether
7373 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007374 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7375 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7376 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007377 return LHS;
7378
Eli Friedman47f77112008-08-22 00:56:42 +00007379 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007380 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007381 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007382 if (OfBlockPointer) {
7383 if (canAssignObjCInterfacesInBlockPointer(
7384 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007385 RHS->getAs<ObjCObjectPointerType>(),
7386 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007387 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007388 return QualType();
7389 }
John McCall9dd450b2009-09-21 23:43:11 +00007390 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7391 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007392 return LHS;
7393
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007394 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007395 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007396 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007397
David Blaikie8a40f702012-01-17 06:56:22 +00007398 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007399}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007400
Fariborz Jahanian97676972011-09-28 21:52:05 +00007401bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7402 const FunctionProtoType *FromFunctionType,
7403 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007404 if (FromFunctionType->hasAnyConsumedParams() !=
7405 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007406 return false;
7407 FunctionProtoType::ExtProtoInfo FromEPI =
7408 FromFunctionType->getExtProtoInfo();
7409 FunctionProtoType::ExtProtoInfo ToEPI =
7410 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007411 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007412 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7413 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007414 return false;
7415 }
7416 return true;
7417}
7418
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007419/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7420/// 'RHS' attributes and returns the merged version; including for function
7421/// return types.
7422QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7423 QualType LHSCan = getCanonicalType(LHS),
7424 RHSCan = getCanonicalType(RHS);
7425 // If two types are identical, they are compatible.
7426 if (LHSCan == RHSCan)
7427 return LHS;
7428 if (RHSCan->isFunctionType()) {
7429 if (!LHSCan->isFunctionType())
7430 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007431 QualType OldReturnType =
7432 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007433 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007434 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007435 QualType ResReturnType =
7436 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7437 if (ResReturnType.isNull())
7438 return QualType();
7439 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7440 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7441 // In either case, use OldReturnType to build the new function type.
7442 const FunctionType *F = LHS->getAs<FunctionType>();
7443 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007444 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7445 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007446 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007447 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007448 return ResultType;
7449 }
7450 }
7451 return QualType();
7452 }
7453
7454 // If the qualifiers are different, the types can still be merged.
7455 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7456 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7457 if (LQuals != RQuals) {
7458 // If any of these qualifiers are different, we have a type mismatch.
7459 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7460 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7461 return QualType();
7462
7463 // Exactly one GC qualifier difference is allowed: __strong is
7464 // okay if the other type has no GC qualifier but is an Objective
7465 // C object pointer (i.e. implicitly strong by default). We fix
7466 // this by pretending that the unqualified type was actually
7467 // qualified __strong.
7468 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7469 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7470 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7471
7472 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7473 return QualType();
7474
7475 if (GC_L == Qualifiers::Strong)
7476 return LHS;
7477 if (GC_R == Qualifiers::Strong)
7478 return RHS;
7479 return QualType();
7480 }
7481
7482 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7483 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7484 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7485 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7486 if (ResQT == LHSBaseQT)
7487 return LHS;
7488 if (ResQT == RHSBaseQT)
7489 return RHS;
7490 }
7491 return QualType();
7492}
7493
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007494//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007495// Integer Predicates
7496//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007497
Jay Foad39c79802011-01-12 09:06:06 +00007498unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007499 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007500 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007501 if (T->isBooleanType())
7502 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007503 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007504 return (unsigned)getTypeSize(T);
7505}
7506
Abramo Bagnara13640492012-09-09 10:21:24 +00007507QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007508 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007509
7510 // Turn <4 x signed int> -> <4 x unsigned int>
7511 if (const VectorType *VTy = T->getAs<VectorType>())
7512 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007513 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007514
7515 // For enums, we return the unsigned version of the base type.
7516 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007517 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007518
7519 const BuiltinType *BTy = T->getAs<BuiltinType>();
7520 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007521 switch (BTy->getKind()) {
7522 case BuiltinType::Char_S:
7523 case BuiltinType::SChar:
7524 return UnsignedCharTy;
7525 case BuiltinType::Short:
7526 return UnsignedShortTy;
7527 case BuiltinType::Int:
7528 return UnsignedIntTy;
7529 case BuiltinType::Long:
7530 return UnsignedLongTy;
7531 case BuiltinType::LongLong:
7532 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007533 case BuiltinType::Int128:
7534 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007535 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007536 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007537 }
7538}
7539
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007540ASTMutationListener::~ASTMutationListener() { }
7541
Richard Smith1fa5d642013-05-11 05:45:24 +00007542void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7543 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007544
7545//===----------------------------------------------------------------------===//
7546// Builtin Type Computation
7547//===----------------------------------------------------------------------===//
7548
7549/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007550/// pointer over the consumed characters. This returns the resultant type. If
7551/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7552/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7553/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007554///
7555/// RequiresICE is filled in on return to indicate whether the value is required
7556/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007557static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007558 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007559 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007560 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007561 // Modifiers.
7562 int HowLong = 0;
7563 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007564 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007565
Chris Lattnerdc226c22010-10-01 22:42:38 +00007566 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007567 bool Done = false;
7568 while (!Done) {
7569 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007570 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007571 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007572 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007573 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007574 case 'S':
7575 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7576 assert(!Signed && "Can't use 'S' modifier multiple times!");
7577 Signed = true;
7578 break;
7579 case 'U':
7580 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007581 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007582 Unsigned = true;
7583 break;
7584 case 'L':
7585 assert(HowLong <= 2 && "Can't have LLLL modifier");
7586 ++HowLong;
7587 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007588 case 'W':
7589 // This modifier represents int64 type.
7590 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7591 switch (Context.getTargetInfo().getInt64Type()) {
7592 default:
7593 llvm_unreachable("Unexpected integer type");
7594 case TargetInfo::SignedLong:
7595 HowLong = 1;
7596 break;
7597 case TargetInfo::SignedLongLong:
7598 HowLong = 2;
7599 break;
7600 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007601 }
7602 }
7603
7604 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007605
Chris Lattnerecd79c62009-06-14 00:45:47 +00007606 // Read the base type.
7607 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007608 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007609 case 'v':
7610 assert(HowLong == 0 && !Signed && !Unsigned &&
7611 "Bad modifiers used with 'v'!");
7612 Type = Context.VoidTy;
7613 break;
Jack Carter24bef982013-08-15 15:16:57 +00007614 case 'h':
7615 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007616 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007617 Type = Context.HalfTy;
7618 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007619 case 'f':
7620 assert(HowLong == 0 && !Signed && !Unsigned &&
7621 "Bad modifiers used with 'f'!");
7622 Type = Context.FloatTy;
7623 break;
7624 case 'd':
7625 assert(HowLong < 2 && !Signed && !Unsigned &&
7626 "Bad modifiers used with 'd'!");
7627 if (HowLong)
7628 Type = Context.LongDoubleTy;
7629 else
7630 Type = Context.DoubleTy;
7631 break;
7632 case 's':
7633 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7634 if (Unsigned)
7635 Type = Context.UnsignedShortTy;
7636 else
7637 Type = Context.ShortTy;
7638 break;
7639 case 'i':
7640 if (HowLong == 3)
7641 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7642 else if (HowLong == 2)
7643 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7644 else if (HowLong == 1)
7645 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7646 else
7647 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7648 break;
7649 case 'c':
7650 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7651 if (Signed)
7652 Type = Context.SignedCharTy;
7653 else if (Unsigned)
7654 Type = Context.UnsignedCharTy;
7655 else
7656 Type = Context.CharTy;
7657 break;
7658 case 'b': // boolean
7659 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7660 Type = Context.BoolTy;
7661 break;
7662 case 'z': // size_t.
7663 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7664 Type = Context.getSizeType();
7665 break;
7666 case 'F':
7667 Type = Context.getCFConstantStringType();
7668 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007669 case 'G':
7670 Type = Context.getObjCIdType();
7671 break;
7672 case 'H':
7673 Type = Context.getObjCSelType();
7674 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007675 case 'M':
7676 Type = Context.getObjCSuperType();
7677 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007678 case 'a':
7679 Type = Context.getBuiltinVaListType();
7680 assert(!Type.isNull() && "builtin va list type not initialized!");
7681 break;
7682 case 'A':
7683 // This is a "reference" to a va_list; however, what exactly
7684 // this means depends on how va_list is defined. There are two
7685 // different kinds of va_list: ones passed by value, and ones
7686 // passed by reference. An example of a by-value va_list is
7687 // x86, where va_list is a char*. An example of by-ref va_list
7688 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7689 // we want this argument to be a char*&; for x86-64, we want
7690 // it to be a __va_list_tag*.
7691 Type = Context.getBuiltinVaListType();
7692 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007693 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007694 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007695 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007696 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007697 break;
7698 case 'V': {
7699 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007700 unsigned NumElements = strtoul(Str, &End, 10);
7701 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007702 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007703
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007704 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7705 RequiresICE, false);
7706 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007707
7708 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007709 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007710 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007711 break;
7712 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007713 case 'E': {
7714 char *End;
7715
7716 unsigned NumElements = strtoul(Str, &End, 10);
7717 assert(End != Str && "Missing vector size");
7718
7719 Str = End;
7720
7721 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7722 false);
7723 Type = Context.getExtVectorType(ElementType, NumElements);
7724 break;
7725 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007726 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007727 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7728 false);
7729 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007730 Type = Context.getComplexType(ElementType);
7731 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007732 }
7733 case 'Y' : {
7734 Type = Context.getPointerDiffType();
7735 break;
7736 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007737 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007738 Type = Context.getFILEType();
7739 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007740 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007741 return QualType();
7742 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007743 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007744 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007745 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007746 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007747 else
7748 Type = Context.getjmp_bufType();
7749
Mike Stump2adb4da2009-07-28 23:47:15 +00007750 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007751 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007752 return QualType();
7753 }
7754 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007755 case 'K':
7756 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7757 Type = Context.getucontext_tType();
7758
7759 if (Type.isNull()) {
7760 Error = ASTContext::GE_Missing_ucontext;
7761 return QualType();
7762 }
7763 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007764 case 'p':
7765 Type = Context.getProcessIDType();
7766 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007767 }
Mike Stump11289f42009-09-09 15:08:12 +00007768
Chris Lattnerdc226c22010-10-01 22:42:38 +00007769 // If there are modifiers and if we're allowed to parse them, go for it.
7770 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007771 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007772 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007773 default: Done = true; --Str; break;
7774 case '*':
7775 case '&': {
7776 // Both pointers and references can have their pointee types
7777 // qualified with an address space.
7778 char *End;
7779 unsigned AddrSpace = strtoul(Str, &End, 10);
7780 if (End != Str && AddrSpace != 0) {
7781 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7782 Str = End;
7783 }
7784 if (c == '*')
7785 Type = Context.getPointerType(Type);
7786 else
7787 Type = Context.getLValueReferenceType(Type);
7788 break;
7789 }
7790 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7791 case 'C':
7792 Type = Type.withConst();
7793 break;
7794 case 'D':
7795 Type = Context.getVolatileType(Type);
7796 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007797 case 'R':
7798 Type = Type.withRestrict();
7799 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007800 }
7801 }
Chris Lattner84733392010-10-01 07:13:18 +00007802
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007803 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007804 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007805
Chris Lattnerecd79c62009-06-14 00:45:47 +00007806 return Type;
7807}
7808
7809/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007810QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007811 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007812 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007813 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007814
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007815 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007816
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007817 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007818 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007819 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7820 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007821 if (Error != GE_None)
7822 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007823
7824 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7825
Chris Lattnerecd79c62009-06-14 00:45:47 +00007826 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007827 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007828 if (Error != GE_None)
7829 return QualType();
7830
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007831 // If this argument is required to be an IntegerConstantExpression and the
7832 // caller cares, fill in the bitmask we return.
7833 if (RequiresICE && IntegerConstantArgs)
7834 *IntegerConstantArgs |= 1 << ArgTypes.size();
7835
Chris Lattnerecd79c62009-06-14 00:45:47 +00007836 // Do array -> pointer decay. The builtin should use the decayed type.
7837 if (Ty->isArrayType())
7838 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007839
Chris Lattnerecd79c62009-06-14 00:45:47 +00007840 ArgTypes.push_back(Ty);
7841 }
7842
David Majnemerba3e5ec2015-03-13 18:26:17 +00007843 if (Id == Builtin::BI__GetExceptionInfo)
7844 return QualType();
7845
Chris Lattnerecd79c62009-06-14 00:45:47 +00007846 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7847 "'.' should only occur at end of builtin type list!");
7848
Reid Kleckner78af0702013-08-27 23:08:25 +00007849 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007850 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7851
7852 bool Variadic = (TypeStr[0] == '.');
7853
7854 // We really shouldn't be making a no-proto type here, especially in C++.
7855 if (ArgTypes.empty() && Variadic)
7856 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007857
John McCalldb40c7f2010-12-14 08:05:40 +00007858 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007859 EPI.ExtInfo = EI;
7860 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007861
Jordan Rose5c382722013-03-08 21:51:21 +00007862 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007863}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007864
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007865static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7866 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007867 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007868 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007869
Rafael Espindola3ae00052013-05-13 00:12:11 +00007870 GVALinkage External = GVA_StrongExternal;
7871 switch (FD->getTemplateSpecializationKind()) {
7872 case TSK_Undeclared:
7873 case TSK_ExplicitSpecialization:
7874 External = GVA_StrongExternal;
7875 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007876
Rafael Espindola3ae00052013-05-13 00:12:11 +00007877 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007878 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007879
David Majnemerc3d07332014-05-15 06:25:57 +00007880 // C++11 [temp.explicit]p10:
7881 // [ Note: The intent is that an inline function that is the subject of
7882 // an explicit instantiation declaration will still be implicitly
7883 // instantiated when used so that the body can be considered for
7884 // inlining, but that no out-of-line copy of the inline function would be
7885 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00007886 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00007887 return GVA_AvailableExternally;
7888
Rafael Espindola3ae00052013-05-13 00:12:11 +00007889 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007890 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00007891 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007892 }
7893
7894 if (!FD->isInlined())
7895 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007896
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007897 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7898 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007899 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007900 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7901
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007902 // GNU or C99 inline semantics. Determine whether this symbol should be
7903 // externally visible.
7904 if (FD->isInlineDefinitionExternallyVisible())
7905 return External;
7906
7907 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00007908 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007909 }
7910
David Majnemer54e3ba52014-04-02 23:17:29 +00007911 // Functions specified with extern and inline in -fms-compatibility mode
7912 // forcibly get emitted. While the body of the function cannot be later
7913 // replaced, the function definition cannot be discarded.
7914 if (FD->getMostRecentDecl()->isMSExternInline())
7915 return GVA_StrongODR;
7916
David Majnemer27d69db2014-04-28 22:17:59 +00007917 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007918}
7919
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007920static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7921 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7922 // dllexport/dllimport on inline functions.
7923 if (D->hasAttr<DLLImportAttr>()) {
7924 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7925 return GVA_AvailableExternally;
7926 } else if (D->hasAttr<DLLExportAttr>()) {
7927 if (L == GVA_DiscardableODR)
7928 return GVA_StrongODR;
7929 }
7930 return L;
7931}
7932
7933GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7934 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7935 FD);
7936}
7937
7938static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7939 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007940 if (!VD->isExternallyVisible())
7941 return GVA_Internal;
7942
David Majnemer27d69db2014-04-28 22:17:59 +00007943 if (VD->isStaticLocal()) {
7944 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7945 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7946 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7947 LexicalContext = LexicalContext->getLexicalParent();
7948
7949 // Let the static local variable inherit it's linkage from the nearest
7950 // enclosing function.
7951 if (LexicalContext)
7952 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007953 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00007954
7955 // GVA_StrongODR function linkage is stronger than what we need,
7956 // downgrade to GVA_DiscardableODR.
7957 // This allows us to discard the variable if we never end up needing it.
7958 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7959 : StaticLocalLinkage;
7960 }
7961
Hans Wennborg56fc62b2014-07-17 20:25:23 +00007962 // MSVC treats in-class initialized static data members as definitions.
7963 // By giving them non-strong linkage, out-of-line definitions won't
7964 // cause link errors.
7965 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7966 return GVA_DiscardableODR;
7967
Richard Smith8809a0c2013-09-27 20:14:12 +00007968 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007969 case TSK_Undeclared:
7970 case TSK_ExplicitSpecialization:
7971 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007972
Rafael Espindola3ae00052013-05-13 00:12:11 +00007973 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00007974 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007975
David Majnemer27d69db2014-04-28 22:17:59 +00007976 case TSK_ExplicitInstantiationDeclaration:
7977 return GVA_AvailableExternally;
7978
Rafael Espindola3ae00052013-05-13 00:12:11 +00007979 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00007980 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007981 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007982
7983 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007984}
7985
Hans Wennborgb0f2f142014-05-15 22:07:49 +00007986GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7987 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7988 VD);
7989}
7990
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007991bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007992 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7993 if (!VD->isFileVarDecl())
7994 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00007995 // Global named register variables (GNU extension) are never emitted.
7996 if (VD->getStorageClass() == SC_Register)
7997 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007998 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7999 // We never need to emit an uninstantiated function template.
8000 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8001 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008002 } else if (isa<OMPThreadPrivateDecl>(D))
8003 return true;
8004 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008005 return false;
8006
8007 // If this is a member of a class template, we do not need to emit it.
8008 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008009 return false;
8010
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008011 // Weak references don't produce any output by themselves.
8012 if (D->hasAttr<WeakRefAttr>())
8013 return false;
8014
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008015 // Aliases and used decls are required.
8016 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8017 return true;
8018
8019 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8020 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008021 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008022 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008023
8024 // Constructors and destructors are required.
8025 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8026 return true;
8027
John McCall6bd2a892013-01-25 22:31:03 +00008028 // The key function for a class is required. This rule only comes
8029 // into play when inline functions can be key functions, though.
8030 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8031 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8032 const CXXRecordDecl *RD = MD->getParent();
8033 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8034 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8035 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8036 return true;
8037 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008038 }
8039 }
8040
8041 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8042
8043 // static, static inline, always_inline, and extern inline functions can
8044 // always be deferred. Normal inline functions can be deferred in C99/C++.
8045 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008046 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8047 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008048 return false;
8049 return true;
8050 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008051
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008052 const VarDecl *VD = cast<VarDecl>(D);
8053 assert(VD->isFileVarDecl() && "Expected file scoped var");
8054
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008055 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8056 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008057 return false;
8058
Richard Smitha0e5e542012-11-12 21:38:00 +00008059 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008060 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008061 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8062 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008063 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008064
Richard Smitha0e5e542012-11-12 21:38:00 +00008065 // Variables that have destruction with side-effects are required.
8066 if (VD->getType().isDestructedType())
8067 return true;
8068
8069 // Variables that have initialization with side-effects are required.
8070 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8071 return true;
8072
8073 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008074}
Charles Davis53c59df2010-08-16 03:33:14 +00008075
Reid Kleckner78af0702013-08-27 23:08:25 +00008076CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8077 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008078 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008079 if (IsCXXMethod)
8080 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008081
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008082 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8083
8084 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008085}
8086
Jay Foad39c79802011-01-12 09:06:06 +00008087bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008088 // Pass through to the C++ ABI object
8089 return ABI->isNearlyEmpty(RD);
8090}
8091
Reid Kleckner96f8f932014-02-05 17:27:08 +00008092VTableContextBase *ASTContext::getVTableContext() {
8093 if (!VTContext.get()) {
8094 if (Target->getCXXABI().isMicrosoft())
8095 VTContext.reset(new MicrosoftVTableContext(*this));
8096 else
8097 VTContext.reset(new ItaniumVTableContext(*this));
8098 }
8099 return VTContext.get();
8100}
8101
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008102MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008103 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008104 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008105 case TargetCXXABI::GenericItanium:
8106 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008107 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008108 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008109 case TargetCXXABI::iOS64:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008110 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008111 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008112 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008113 }
David Blaikie83d382b2011-09-23 05:06:16 +00008114 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008115}
8116
Charles Davis53c59df2010-08-16 03:33:14 +00008117CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008118
8119size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008120 return ASTRecordLayouts.getMemorySize() +
8121 llvm::capacity_in_bytes(ObjCLayouts) +
8122 llvm::capacity_in_bytes(KeyFunctions) +
8123 llvm::capacity_in_bytes(ObjCImpls) +
8124 llvm::capacity_in_bytes(BlockVarCopyInits) +
8125 llvm::capacity_in_bytes(DeclAttrs) +
8126 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8127 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8128 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8129 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8130 llvm::capacity_in_bytes(OverriddenMethods) +
8131 llvm::capacity_in_bytes(Types) +
8132 llvm::capacity_in_bytes(VariableArrayTypes) +
8133 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008134}
Ted Kremenek540017e2011-10-06 05:00:56 +00008135
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008136/// getIntTypeForBitwidth -
8137/// sets integer QualTy according to specified details:
8138/// bitwidth, signed/unsigned.
8139/// Returns empty type if there is no appropriate target types.
8140QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8141 unsigned Signed) const {
8142 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8143 CanQualType QualTy = getFromTargetType(Ty);
8144 if (!QualTy && DestWidth == 128)
8145 return Signed ? Int128Ty : UnsignedInt128Ty;
8146 return QualTy;
8147}
8148
8149/// getRealTypeForBitwidth -
8150/// sets floating point QualTy according to specified bitwidth.
8151/// Returns empty type if there is no appropriate target types.
8152QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8153 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8154 switch (Ty) {
8155 case TargetInfo::Float:
8156 return FloatTy;
8157 case TargetInfo::Double:
8158 return DoubleTy;
8159 case TargetInfo::LongDouble:
8160 return LongDoubleTy;
8161 case TargetInfo::NoFloat:
8162 return QualType();
8163 }
8164
8165 llvm_unreachable("Unhandled TargetInfo::RealType value");
8166}
8167
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008168void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8169 if (Number > 1)
8170 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008171}
8172
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008173unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8174 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8175 MangleNumbers.find(ND);
8176 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008177}
8178
David Majnemer2206bf52014-03-05 08:57:59 +00008179void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8180 if (Number > 1)
8181 StaticLocalNumbers[VD] = Number;
8182}
8183
8184unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8185 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8186 StaticLocalNumbers.find(VD);
8187 return I != StaticLocalNumbers.end() ? I->second : 1;
8188}
8189
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008190MangleNumberingContext &
8191ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008192 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8193 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8194 if (!MCtx)
8195 MCtx = createMangleNumberingContext();
8196 return *MCtx;
8197}
8198
8199MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8200 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008201}
8202
David Majnemere7a818f2015-03-06 18:53:55 +00008203const CXXConstructorDecl *
8204ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8205 return ABI->getCopyConstructorForExceptionObject(
8206 cast<CXXRecordDecl>(RD->getFirstDecl()));
8207}
8208
8209void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8210 CXXConstructorDecl *CD) {
8211 return ABI->addCopyConstructorForExceptionObject(
8212 cast<CXXRecordDecl>(RD->getFirstDecl()),
8213 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8214}
8215
David Majnemerdfa6d202015-03-11 18:36:39 +00008216void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8217 unsigned ParmIdx, Expr *DAE) {
8218 ABI->addDefaultArgExprForConstructor(
8219 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8220}
8221
8222Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8223 unsigned ParmIdx) {
8224 return ABI->getDefaultArgExprForConstructor(
8225 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8226}
8227
Ted Kremenek540017e2011-10-06 05:00:56 +00008228void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8229 ParamIndices[D] = index;
8230}
8231
8232unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8233 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8234 assert(I != ParamIndices.end() &&
8235 "ParmIndices lacks entry set by ParmVarDecl");
8236 return I->second;
8237}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008238
Richard Smithe6c01442013-06-05 00:46:14 +00008239APValue *
8240ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8241 bool MayCreate) {
8242 assert(E && E->getStorageDuration() == SD_Static &&
8243 "don't need to cache the computed value for this temporary");
8244 if (MayCreate)
8245 return &MaterializedTemporaryValues[E];
8246
8247 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8248 MaterializedTemporaryValues.find(E);
Craig Topper36250ad2014-05-12 05:36:57 +00008249 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
Richard Smithe6c01442013-06-05 00:46:14 +00008250}
8251
Fariborz Jahanian615de762013-05-28 17:37:39 +00008252bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8253 const llvm::Triple &T = getTargetInfo().getTriple();
8254 if (!T.isOSDarwin())
8255 return false;
8256
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008257 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8258 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8259 return false;
8260
Fariborz Jahanian615de762013-05-28 17:37:39 +00008261 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8262 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8263 uint64_t Size = sizeChars.getQuantity();
8264 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8265 unsigned Align = alignChars.getQuantity();
8266 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8267 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8268}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008269
8270namespace {
8271
8272 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8273 /// parents as defined by the \c RecursiveASTVisitor.
8274 ///
8275 /// Note that the relationship described here is purely in terms of AST
8276 /// traversal - there are other relationships (for example declaration context)
8277 /// in the AST that are better modeled by special matchers.
8278 ///
8279 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8280 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8281
8282 public:
8283 /// \brief Builds and returns the translation unit's parent map.
8284 ///
8285 /// The caller takes ownership of the returned \c ParentMap.
8286 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8287 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8288 Visitor.TraverseDecl(&TU);
8289 return Visitor.Parents;
8290 }
8291
8292 private:
8293 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8294
8295 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8296 }
8297
8298 bool shouldVisitTemplateInstantiations() const {
8299 return true;
8300 }
8301 bool shouldVisitImplicitCode() const {
8302 return true;
8303 }
8304 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8305 // are not triggered during data recursion.
8306 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8307 return false;
8308 }
8309
8310 template <typename T>
8311 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008312 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008313 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008314 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008315 // FIXME: Currently we add the same parent multiple times, but only
8316 // when no memoization data is available for the type.
8317 // For example when we visit all subexpressions of template
8318 // instantiations; this is suboptimal, but benign: the only way to
8319 // visit those is with hasAncestor / hasParent, and those do not create
8320 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008321 // The plan is to enable DynTypedNode to be storable in a map or hash
8322 // map. The main problem there is to implement hash functions /
8323 // comparison operators for all types that DynTypedNode supports that
8324 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008325 auto &NodeOrVector = (*Parents)[Node];
8326 if (NodeOrVector.isNull()) {
8327 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008328 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008329 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8330 auto *Node =
8331 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8332 auto *Vector = new ASTContext::ParentVector(1, *Node);
8333 NodeOrVector = Vector;
8334 delete Node;
8335 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008336 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008337
8338 auto *Vector =
8339 NodeOrVector.template get<ASTContext::ParentVector *>();
8340 // Skip duplicates for types that have memoization data.
8341 // We must check that the type has memoization data before calling
8342 // std::find() because DynTypedNode::operator== can't compare all
8343 // types.
8344 bool Found = ParentStack.back().getMemoizationData() &&
8345 std::find(Vector->begin(), Vector->end(),
8346 ParentStack.back()) != Vector->end();
8347 if (!Found)
8348 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008349 }
8350 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008351 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8352 bool Result = (this ->* traverse) (Node);
8353 ParentStack.pop_back();
8354 return Result;
8355 }
8356
8357 bool TraverseDecl(Decl *DeclNode) {
8358 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8359 }
8360
8361 bool TraverseStmt(Stmt *StmtNode) {
8362 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8363 }
8364
8365 ASTContext::ParentMap *Parents;
8366 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8367
8368 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8369 };
8370
8371} // end namespace
8372
Benjamin Kramer07935292014-10-04 17:01:26 +00008373ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008374ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8375 assert(Node.getMemoizationData() &&
8376 "Invariant broken: only nodes that support memoization may be "
8377 "used in the parent map.");
8378 if (!AllParents) {
8379 // We always need to run over the whole translation unit, as
8380 // hasAncestor can escape any subtree.
8381 AllParents.reset(
8382 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8383 }
8384 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8385 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008386 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008387 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008388 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8389 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008390 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008391 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008392}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008393
8394bool
8395ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8396 const ObjCMethodDecl *MethodImpl) {
8397 // No point trying to match an unavailable/deprecated mothod.
8398 if (MethodDecl->hasAttr<UnavailableAttr>()
8399 || MethodDecl->hasAttr<DeprecatedAttr>())
8400 return false;
8401 if (MethodDecl->getObjCDeclQualifier() !=
8402 MethodImpl->getObjCDeclQualifier())
8403 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008404 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008405 return false;
8406
8407 if (MethodDecl->param_size() != MethodImpl->param_size())
8408 return false;
8409
8410 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8411 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8412 EF = MethodDecl->param_end();
8413 IM != EM && IF != EF; ++IM, ++IF) {
8414 const ParmVarDecl *DeclVar = (*IF);
8415 const ParmVarDecl *ImplVar = (*IM);
8416 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8417 return false;
8418 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8419 return false;
8420 }
8421 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8422
8423}
Richard Smith053f6c62014-05-16 23:01:30 +00008424
8425// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8426// doesn't include ASTContext.h
8427template
8428clang::LazyGenerationalUpdatePtr<
8429 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8430clang::LazyGenerationalUpdatePtr<
8431 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8432 const clang::ASTContext &Ctx, Decl *Value);