blob: 43040b45e900b84e49764a8cd5902d9ff98b94c1 [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();
66 CommentsLoaded = true;
67 }
68
69 assert(D);
70
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000071 // User can not attach documentation to implicit declarations.
72 if (D->isImplicit())
73 return NULL;
74
Dmitri Gribenkob2610882012-08-14 17:17:18 +000075 // User can not attach documentation to implicit instantiations.
76 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
77 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
78 return NULL;
79 }
80
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000081 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
82 if (VD->isStaticDataMember() &&
83 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
84 return NULL;
85 }
86
87 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
88 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
89 return NULL;
90 }
91
Dmitri Gribenko01b06512013-01-27 21:18:39 +000092 if (const ClassTemplateSpecializationDecl *CTSD =
93 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
94 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
95 if (TSK == TSK_ImplicitInstantiation ||
96 TSK == TSK_Undeclared)
97 return NULL;
98 }
99
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000100 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
101 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
102 return NULL;
103 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000104 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
105 // When tag declaration (but not definition!) is part of the
106 // decl-specifier-seq of some other declaration, it doesn't get comment
107 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
108 return NULL;
109 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000110 // TODO: handle comments for function parameters properly.
111 if (isa<ParmVarDecl>(D))
112 return NULL;
113
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000114 // TODO: we could look up template parameter documentation in the template
115 // documentation.
116 if (isa<TemplateTypeParmDecl>(D) ||
117 isa<NonTypeTemplateParmDecl>(D) ||
118 isa<TemplateTemplateParmDecl>(D))
119 return NULL;
120
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000121 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000122
123 // If there are no comments anywhere, we won't find anything.
124 if (RawComments.empty())
125 return NULL;
126
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000127 // Find declaration location.
128 // For Objective-C declarations we generally don't expect to have multiple
129 // declarators, thus use declaration starting location as the "declaration
130 // location".
131 // For all other declarations multiple declarators are used quite frequently,
132 // so we use the location of the identifier as the "declaration location".
133 SourceLocation DeclLoc;
134 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000135 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000136 isa<RedeclarableTemplateDecl>(D) ||
137 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000138 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000139 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000140 DeclLoc = D->getLocation();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000141 // If location of the typedef name is in a macro, it is because being
142 // declared via a macro. Try using declaration's starting location
143 // as the "declaration location".
144 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
145 DeclLoc = D->getLocStart();
146 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000148 // If the declaration doesn't map directly to a location in a file, we
149 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
151 return NULL;
152
153 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000154 ArrayRef<RawComment *>::iterator Comment;
155 {
156 // When searching for comments during parsing, the comment we are looking
157 // for is usually among the last two comments we parsed -- check them
158 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000159 RawComment CommentAtDeclLoc(
160 SourceMgr, SourceRange(DeclLoc), false,
161 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000162 BeforeThanCompare<RawComment> Compare(SourceMgr);
163 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
164 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
165 if (!Found && RawComments.size() >= 2) {
166 MaybeBeforeDecl--;
167 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
168 }
169
170 if (Found) {
171 Comment = MaybeBeforeDecl + 1;
172 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
173 &CommentAtDeclLoc, Compare));
174 } else {
175 // Slow path.
176 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
177 &CommentAtDeclLoc, Compare);
178 }
179 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000180
181 // Decompose the location for the declaration and find the beginning of the
182 // file buffer.
183 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
184
185 // First check whether we have a trailing comment.
186 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000187 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000188 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000189 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000190 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000191 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000192 // Check that Doxygen trailing comment comes after the declaration, starts
193 // on the same line and in the same file as the declaration.
194 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
195 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
196 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
197 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000198 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199 }
200 }
201
202 // The comment just after the declaration was not a trailing comment.
203 // Let's look at the previous comment.
204 if (Comment == RawComments.begin())
205 return NULL;
206 --Comment;
207
208 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000209 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000210 return NULL;
211
212 // Decompose the end of the comment.
213 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000214 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000215
216 // If the comment and the declaration aren't in the same file, then they
217 // aren't related.
218 if (DeclLocDecomp.first != CommentEndDecomp.first)
219 return NULL;
220
221 // Get the corresponding buffer.
222 bool Invalid = false;
223 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
224 &Invalid).data();
225 if (Invalid)
226 return NULL;
227
228 // Extract text between the comment and declaration.
229 StringRef Text(Buffer + CommentEndDecomp.second,
230 DeclLocDecomp.second - CommentEndDecomp.second);
231
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000232 // There should be no other declarations or preprocessor directives between
233 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000234 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000235 return NULL;
236
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000237 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000238}
239
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000240namespace {
241/// If we have a 'templated' declaration for a template, adjust 'D' to
242/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000243/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000244const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000246 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000247 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000248 return FTD;
249
250 // Nothing to do if function is not an implicit instantiation.
251 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
252 return D;
253
254 // Function is an implicit instantiation of a function template?
255 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
256 return FTD;
257
258 // Function is instantiated from a member definition of a class template?
259 if (const FunctionDecl *MemberDecl =
260 FD->getInstantiatedFromMemberFunction())
261 return MemberDecl;
262
263 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
266 // Static data member is instantiated from a member definition of a class
267 // template?
268 if (VD->isStaticDataMember())
269 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
270 return MemberDecl;
271
272 return D;
273 }
274 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
275 // Is this class declaration part of a class template?
276 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
277 return CTD;
278
279 // Class is an implicit instantiation of a class template or partial
280 // specialization?
281 if (const ClassTemplateSpecializationDecl *CTSD =
282 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
283 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
284 return D;
285 llvm::PointerUnion<ClassTemplateDecl *,
286 ClassTemplatePartialSpecializationDecl *>
287 PU = CTSD->getSpecializedTemplateOrPartial();
288 return PU.is<ClassTemplateDecl*>() ?
289 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
290 static_cast<const Decl*>(
291 PU.get<ClassTemplatePartialSpecializationDecl *>());
292 }
293
294 // Class is instantiated from a member definition of a class template?
295 if (const MemberSpecializationInfo *Info =
296 CRD->getMemberSpecializationInfo())
297 return Info->getInstantiatedFrom();
298
299 return D;
300 }
301 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
302 // Enum is instantiated from a member definition of a class template?
303 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
304 return MemberDecl;
305
306 return D;
307 }
308 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000309 return D;
310}
311} // unnamed namespace
312
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000313const RawComment *ASTContext::getRawCommentForAnyRedecl(
314 const Decl *D,
315 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000316 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000318 // Check whether we have cached a comment for this declaration already.
319 {
320 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
321 RedeclComments.find(D);
322 if (Pos != RedeclComments.end()) {
323 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000324 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
325 if (OriginalDecl)
326 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000327 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000328 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000329 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000330 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000331
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000332 // Search for comments attached to declarations in the redeclaration chain.
333 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000334 const Decl *OriginalDeclForRC = NULL;
Aaron Ballman86c93902014-03-06 23:45:36 +0000335 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000336 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000337 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000338 if (Pos != RedeclComments.end()) {
339 const RawCommentAndCacheFlags &Raw = Pos->second;
340 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
341 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000342 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 break;
344 }
345 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000346 RC = getRawCommentForDeclNoCache(I);
347 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 RawCommentAndCacheFlags Raw;
349 if (RC) {
350 Raw.setRaw(RC);
351 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
352 } else
353 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 Raw.setOriginalDecl(I);
355 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 if (RC)
357 break;
358 }
359 }
360
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000361 // If we found a comment, it should be a documentation comment.
362 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000364 if (OriginalDecl)
365 *OriginalDecl = OriginalDeclForRC;
366
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 // Update cache for every declaration in the redeclaration chain.
368 RawCommentAndCacheFlags Raw;
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000371 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000372
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 for (auto I : D->redecls()) {
374 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
376 R = Raw;
377 }
378
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000379 return RC;
380}
381
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000382static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
383 SmallVectorImpl<const NamedDecl *> &Redeclared) {
384 const DeclContext *DC = ObjCMethod->getDeclContext();
385 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
386 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
387 if (!ID)
388 return;
389 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000390 for (ObjCInterfaceDecl::known_extensions_iterator
391 Ext = ID->known_extensions_begin(),
392 ExtEnd = ID->known_extensions_end();
393 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000394 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000395 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000396 ObjCMethod->isInstanceMethod()))
397 Redeclared.push_back(RedeclaredMethod);
398 }
399 }
400}
401
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000402comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
403 const Decl *D) const {
404 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
405 ThisDeclInfo->CommentDecl = D;
406 ThisDeclInfo->IsFilled = false;
407 ThisDeclInfo->fill();
408 ThisDeclInfo->CommentDecl = FC->getDecl();
409 comments::FullComment *CFC =
410 new (*this) comments::FullComment(FC->getBlocks(),
411 ThisDeclInfo);
412 return CFC;
413
414}
415
Richard Smithb39b9d52013-05-21 05:24:00 +0000416comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
417 const RawComment *RC = getRawCommentForDeclNoCache(D);
418 return RC ? RC->parse(*this, 0, D) : 0;
419}
420
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000421comments::FullComment *ASTContext::getCommentForDecl(
422 const Decl *D,
423 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000424 if (D->isInvalidDecl())
425 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000426 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000427
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000428 const Decl *Canonical = D->getCanonicalDecl();
429 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
430 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000431
432 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000434 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000435 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000436 return CFC;
437 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000438 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000439 }
440
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000441 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000442
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000443 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444 if (!RC) {
445 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000446 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000447 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000448 if (OMD && OMD->isPropertyAccessor())
449 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
450 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
451 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000452 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000453 addRedeclaredMethods(OMD, Overridden);
454 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000455 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
456 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
457 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000459 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000460 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000461 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000462 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000463 if (const TagType *TT = QT->getAs<TagType>())
464 if (const Decl *TD = TT->getDecl())
465 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000467 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000468 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
469 while (IC->getSuperClass()) {
470 IC = IC->getSuperClass();
471 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
472 return cloneFullComment(FC, D);
473 }
474 }
475 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
476 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
477 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
478 return cloneFullComment(FC, D);
479 }
480 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
481 if (!(RD = RD->getDefinition()))
482 return NULL;
483 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000484 for (const auto &I : RD->bases()) {
485 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000487 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000488 if (Ty.isNull())
489 continue;
490 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
491 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
492 continue;
493
494 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
495 return cloneFullComment(FC, D);
496 }
497 }
498 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000499 for (const auto &I : RD->vbases()) {
500 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000501 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000502 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000503 if (Ty.isNull())
504 continue;
505 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
506 if (!(VirtualBase= VirtualBase->getDefinition()))
507 continue;
508 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
509 return cloneFullComment(FC, D);
510 }
511 }
512 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000513 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000514 }
515
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000516 // If the RawComment was attached to other redeclaration of this Decl, we
517 // should parse the comment in context of that other Decl. This is important
518 // because comments can contain references to parameter names which can be
519 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000520 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000521 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000522
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000523 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000524 ParsedComments[Canonical] = FC;
525 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000526}
527
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000528void
529ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
530 TemplateTemplateParmDecl *Parm) {
531 ID.AddInteger(Parm->getDepth());
532 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000533 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000534
535 TemplateParameterList *Params = Parm->getTemplateParameters();
536 ID.AddInteger(Params->size());
537 for (TemplateParameterList::const_iterator P = Params->begin(),
538 PEnd = Params->end();
539 P != PEnd; ++P) {
540 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
541 ID.AddInteger(0);
542 ID.AddBoolean(TTP->isParameterPack());
543 continue;
544 }
545
546 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
547 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000548 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000549 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000550 if (NTTP->isExpandedParameterPack()) {
551 ID.AddBoolean(true);
552 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000553 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
554 QualType T = NTTP->getExpansionType(I);
555 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
556 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000557 } else
558 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000559 continue;
560 }
561
562 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
563 ID.AddInteger(2);
564 Profile(ID, TTP);
565 }
566}
567
568TemplateTemplateParmDecl *
569ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000570 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000571 // Check if we already have a canonical template template parameter.
572 llvm::FoldingSetNodeID ID;
573 CanonicalTemplateTemplateParm::Profile(ID, TTP);
574 void *InsertPos = 0;
575 CanonicalTemplateTemplateParm *Canonical
576 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
577 if (Canonical)
578 return Canonical->getParam();
579
580 // Build a canonical template parameter list.
581 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000582 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000583 CanonParams.reserve(Params->size());
584 for (TemplateParameterList::const_iterator P = Params->begin(),
585 PEnd = Params->end();
586 P != PEnd; ++P) {
587 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
588 CanonParams.push_back(
589 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000590 SourceLocation(),
591 SourceLocation(),
592 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 TTP->getIndex(), 0, false,
594 TTP->isParameterPack()));
595 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000596 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
597 QualType T = getCanonicalType(NTTP->getType());
598 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
599 NonTypeTemplateParmDecl *Param;
600 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<QualType, 2> ExpandedTypes;
602 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000603 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
604 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
605 ExpandedTInfos.push_back(
606 getTrivialTypeSourceInfo(ExpandedTypes.back()));
607 }
608
609 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000610 SourceLocation(),
611 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000612 NTTP->getDepth(),
613 NTTP->getPosition(), 0,
614 T,
615 TInfo,
616 ExpandedTypes.data(),
617 ExpandedTypes.size(),
618 ExpandedTInfos.data());
619 } else {
620 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000621 SourceLocation(),
622 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000623 NTTP->getDepth(),
624 NTTP->getPosition(), 0,
625 T,
626 NTTP->isParameterPack(),
627 TInfo);
628 }
629 CanonParams.push_back(Param);
630
631 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000632 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
633 cast<TemplateTemplateParmDecl>(*P)));
634 }
635
636 TemplateTemplateParmDecl *CanonTTP
637 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
638 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000639 TTP->getPosition(),
640 TTP->isParameterPack(),
641 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000642 TemplateParameterList::Create(*this, SourceLocation(),
643 SourceLocation(),
644 CanonParams.data(),
645 CanonParams.size(),
646 SourceLocation()));
647
648 // Get the new insert position for the node we care about.
649 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
650 assert(Canonical == 0 && "Shouldn't be in the map!");
651 (void)Canonical;
652
653 // Create the canonical template template parameter entry.
654 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
655 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
656 return CanonTTP;
657}
658
Charles Davis53c59df2010-08-16 03:33:14 +0000659CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000660 if (!LangOpts.CPlusPlus) return 0;
661
John McCall359b8852013-01-25 22:30:49 +0000662 switch (T.getCXXABI().getKind()) {
663 case TargetCXXABI::GenericARM:
664 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000665 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000666 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000667 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000668 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000669 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000670 return CreateMicrosoftCXXABI(*this);
671 }
David Blaikie8a40f702012-01-17 06:56:22 +0000672 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000673}
674
Douglas Gregore8bbc122011-09-02 00:18:52 +0000675static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000676 const LangOptions &LOpts) {
677 if (LOpts.FakeAddressSpaceMap) {
678 // The fake address space map must have a distinct entry for each
679 // language-specific address space.
680 static const unsigned FakeAddrSpaceMap[] = {
681 1, // opencl_global
682 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000683 3, // opencl_constant
684 4, // cuda_device
685 5, // cuda_constant
686 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000687 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000688 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000689 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000690 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000691 }
692}
693
David Tweed31d09b02013-09-13 12:04:22 +0000694static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
695 const LangOptions &LangOpts) {
696 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000697 case LangOptions::ASMM_Target:
698 return TI.useAddressSpaceMapMangling();
699 case LangOptions::ASMM_On:
700 return true;
701 case LangOptions::ASMM_Off:
702 return false;
703 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000704 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000705}
706
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000707ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000709 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000710 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 unsigned size_reserve,
712 bool DelayInitialization)
713 : FunctionProtoTypes(this_()),
714 TemplateSpecializationTypes(this_()),
715 DependentTemplateSpecializationTypes(this_()),
716 SubstTemplateTemplateParmPacks(this_()),
717 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000718 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000719 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000720 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000721 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000722 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000723 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000724 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
725 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
726 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000727 NullTypeSourceInfo(QualType()),
728 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000729 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000730 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000731 Idents(idents), Selectors(sels),
732 BuiltinInfo(builtins),
733 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000734 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000735 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000736 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000737 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000738{
Mike Stump11289f42009-09-09 15:08:12 +0000739 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000740 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000741
742 if (!DelayInitialization) {
743 assert(t && "No target supplied for ASTContext initialization");
744 InitBuiltinTypes(*t);
745 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000746}
747
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000748ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000749 // Release the DenseMaps associated with DeclContext objects.
750 // FIXME: Is this the ideal solution?
751 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000752
Manuel Klimeka7328992013-06-03 13:51:33 +0000753 // Call all of the deallocation functions on all of their targets.
754 for (DeallocationMap::const_iterator I = Deallocations.begin(),
755 E = Deallocations.end(); I != E; ++I)
756 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
757 (I->first)((I->second)[J]);
758
Ted Kremenek076baeb2010-06-08 23:00:58 +0000759 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000760 // because they can contain DenseMaps.
761 for (llvm::DenseMap<const ObjCContainerDecl*,
762 const ASTRecordLayout*>::iterator
763 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
764 // Increment in loop to prevent using deallocated memory.
765 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
766 R->Destroy(*this);
767
Ted Kremenek076baeb2010-06-08 23:00:58 +0000768 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
769 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.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 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000774
775 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
776 AEnd = DeclAttrs.end();
777 A != AEnd; ++A)
778 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000779
Reid Kleckner588c9372014-02-19 23:44:52 +0000780 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000781}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000782
Douglas Gregor1a809332010-05-23 18:26:36 +0000783void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000784 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000785}
786
Mike Stump11289f42009-09-09 15:08:12 +0000787void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000788ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
789 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000790}
791
Chris Lattner4eb445d2007-01-26 01:27:23 +0000792void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000793 llvm::errs() << "\n*** AST Context Stats:\n";
794 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000795
Douglas Gregora30d0462009-05-26 14:40:08 +0000796 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000797#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000798#define ABSTRACT_TYPE(Name, Parent)
799#include "clang/AST/TypeNodes.def"
800 0 // Extra
801 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000802
Chris Lattner4eb445d2007-01-26 01:27:23 +0000803 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
804 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000805 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000806 }
807
Douglas Gregora30d0462009-05-26 14:40:08 +0000808 unsigned Idx = 0;
809 unsigned TotalBytes = 0;
810#define TYPE(Name, Parent) \
811 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000812 llvm::errs() << " " << counts[Idx] << " " << #Name \
813 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 TotalBytes += counts[Idx] * sizeof(Name##Type); \
815 ++Idx;
816#define ABSTRACT_TYPE(Name, Parent)
817#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000818
Chandler Carruth3c147a72011-07-04 05:32:14 +0000819 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
820
Douglas Gregor7454c562010-07-02 20:37:36 +0000821 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000822 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
823 << NumImplicitDefaultConstructors
824 << " implicit default constructors created\n";
825 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
826 << NumImplicitCopyConstructors
827 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000828 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000829 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
830 << NumImplicitMoveConstructors
831 << " implicit move constructors created\n";
832 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
833 << NumImplicitCopyAssignmentOperators
834 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000835 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
837 << NumImplicitMoveAssignmentOperators
838 << " implicit move assignment operators created\n";
839 llvm::errs() << NumImplicitDestructorsDeclared << "/"
840 << NumImplicitDestructors
841 << " implicit destructors created\n";
842
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000843 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000844 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000845 ExternalSource->PrintStats();
846 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000847
Douglas Gregor5b11d492010-07-25 17:53:33 +0000848 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000849}
850
Alp Toker2dea15b2013-12-17 01:22:38 +0000851RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
852 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000853 SourceLocation Loc;
854 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000855 if (getLangOpts().CPlusPlus)
856 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
857 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000858 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000859 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
860 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000861 NewDecl->setImplicit();
862 return NewDecl;
863}
864
865TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
866 StringRef Name) const {
867 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
868 TypedefDecl *NewDecl = TypedefDecl::Create(
869 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
870 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
871 NewDecl->setImplicit();
872 return NewDecl;
873}
874
Douglas Gregor801c99d2011-08-12 06:49:56 +0000875TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000876 if (!Int128Decl)
877 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000878 return Int128Decl;
879}
880
881TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000882 if (!UInt128Decl)
883 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000884 return UInt128Decl;
885}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000886
Nico Webere1687c52013-06-20 21:44:55 +0000887TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000888 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000889 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000890 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000891
Nico Webere1687c52013-06-20 21:44:55 +0000892 return Float128StubDecl;
893}
894
John McCall48f2d582009-10-23 23:03:21 +0000895void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000896 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000897 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000898 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000899}
900
Douglas Gregore8bbc122011-09-02 00:18:52 +0000901void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
902 assert((!this->Target || this->Target == &Target) &&
903 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000904 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000905
Douglas Gregore8bbc122011-09-02 00:18:52 +0000906 this->Target = &Target;
907
908 ABI.reset(createCXXABI(Target));
909 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000910 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000911
Chris Lattner970e54e2006-11-12 00:37:36 +0000912 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000913 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000914
Chris Lattner970e54e2006-11-12 00:37:36 +0000915 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000916 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000917 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000918 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000919 InitBuiltinType(CharTy, BuiltinType::Char_S);
920 else
921 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000922 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000923 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
924 InitBuiltinType(ShortTy, BuiltinType::Short);
925 InitBuiltinType(IntTy, BuiltinType::Int);
926 InitBuiltinType(LongTy, BuiltinType::Long);
927 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000928
Chris Lattner970e54e2006-11-12 00:37:36 +0000929 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000930 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
931 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
932 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
933 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
934 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner970e54e2006-11-12 00:37:36 +0000936 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000937 InitBuiltinType(FloatTy, BuiltinType::Float);
938 InitBuiltinType(DoubleTy, BuiltinType::Double);
939 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000940
Chris Lattnerf122cef2009-04-30 02:43:43 +0000941 // GNU extension, 128-bit integers.
942 InitBuiltinType(Int128Ty, BuiltinType::Int128);
943 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
944
Hans Wennborg0d81e012013-05-10 10:08:40 +0000945 // C++ 3.9.1p5
946 if (TargetInfo::isTypeSigned(Target.getWCharType()))
947 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
948 else // -fshort-wchar makes wchar_t be unsigned.
949 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
950 if (LangOpts.CPlusPlus && LangOpts.WChar)
951 WideCharTy = WCharTy;
952 else {
953 // C99 (or C++ using -fno-wchar).
954 WideCharTy = getFromTargetType(Target.getWCharType());
955 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000956
James Molloy36365542012-05-04 10:55:22 +0000957 WIntTy = getFromTargetType(Target.getWIntType());
958
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000959 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
960 InitBuiltinType(Char16Ty, BuiltinType::Char16);
961 else // C99
962 Char16Ty = getFromTargetType(Target.getChar16Type());
963
964 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
965 InitBuiltinType(Char32Ty, BuiltinType::Char32);
966 else // C99
967 Char32Ty = getFromTargetType(Target.getChar32Type());
968
Douglas Gregor4619e432008-12-05 23:32:09 +0000969 // Placeholder type for type-dependent expressions whose type is
970 // completely unknown. No code should ever check a type against
971 // DependentTy and users should never see it; however, it is here to
972 // help diagnose failures to properly check for type-dependent
973 // expressions.
974 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000975
John McCall36e7fe32010-10-12 00:20:44 +0000976 // Placeholder type for functions.
977 InitBuiltinType(OverloadTy, BuiltinType::Overload);
978
John McCall0009fcc2011-04-26 20:42:42 +0000979 // Placeholder type for bound members.
980 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
981
John McCall526ab472011-10-25 17:37:35 +0000982 // Placeholder type for pseudo-objects.
983 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
984
John McCall31996342011-04-07 08:22:57 +0000985 // "any" type; useful for debugger-like clients.
986 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
987
John McCall8a6b59a2011-10-17 18:09:15 +0000988 // Placeholder type for unbridged ARC casts.
989 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
990
Eli Friedman34866c72012-08-31 00:14:07 +0000991 // Placeholder type for builtin functions.
992 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
993
Chris Lattner970e54e2006-11-12 00:37:36 +0000994 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000995 FloatComplexTy = getComplexType(FloatTy);
996 DoubleComplexTy = getComplexType(DoubleTy);
997 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000999 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001000 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1001 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001002 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001003
1004 if (LangOpts.OpenCL) {
1005 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1006 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1007 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1008 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1009 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1010 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001011
Guy Benyei61054192013-02-07 10:55:47 +00001012 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001013 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001014 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001015
1016 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001017 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1018 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001019
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001020 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001021
1022 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001023
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001024 // void * type
1025 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001026
1027 // nullptr type (C++0x 2.14.7)
1028 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001029
1030 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1031 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001032
1033 // Builtin type used to help define __builtin_va_list.
1034 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001035}
1036
David Blaikie9c902b52011-09-25 23:23:43 +00001037DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001038 return SourceMgr.getDiagnostics();
1039}
1040
Douglas Gregor561eceb2010-08-30 16:49:28 +00001041AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1042 AttrVec *&Result = DeclAttrs[D];
1043 if (!Result) {
1044 void *Mem = Allocate(sizeof(AttrVec));
1045 Result = new (Mem) AttrVec;
1046 }
1047
1048 return *Result;
1049}
1050
1051/// \brief Erase the attributes corresponding to the given declaration.
1052void ASTContext::eraseDeclAttrs(const Decl *D) {
1053 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1054 if (Pos != DeclAttrs.end()) {
1055 Pos->second->~AttrVec();
1056 DeclAttrs.erase(Pos);
1057 }
1058}
1059
Larisse Voufo39a1e502013-08-06 01:03:05 +00001060// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001061MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001062ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001063 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001064 return getTemplateOrSpecializationInfo(Var)
1065 .dyn_cast<MemberSpecializationInfo *>();
1066}
1067
1068ASTContext::TemplateOrSpecializationInfo
1069ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1070 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1071 TemplateOrInstantiation.find(Var);
1072 if (Pos == TemplateOrInstantiation.end())
1073 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001074
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001075 return Pos->second;
1076}
1077
Mike Stump11289f42009-09-09 15:08:12 +00001078void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001079ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001080 TemplateSpecializationKind TSK,
1081 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001082 assert(Inst->isStaticDataMember() && "Not a static data member");
1083 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001084 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1085 Tmpl, TSK, PointOfInstantiation));
1086}
1087
1088void
1089ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1090 TemplateOrSpecializationInfo TSI) {
1091 assert(!TemplateOrInstantiation[Inst] &&
1092 "Already noted what the variable was instantiated from");
1093 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001094}
1095
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001096FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1097 const FunctionDecl *FD){
1098 assert(FD && "Specialization is 0");
1099 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001100 = ClassScopeSpecializationPattern.find(FD);
1101 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001102 return 0;
1103
1104 return Pos->second;
1105}
1106
1107void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1108 FunctionDecl *Pattern) {
1109 assert(FD && "Specialization is 0");
1110 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001111 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001112}
1113
John McCalle61f2ba2009-11-18 02:36:19 +00001114NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001115ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001116 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001117 = InstantiatedFromUsingDecl.find(UUD);
1118 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001119 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001120
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001121 return Pos->second;
1122}
1123
1124void
John McCallb96ec562009-12-04 22:46:56 +00001125ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1126 assert((isa<UsingDecl>(Pattern) ||
1127 isa<UnresolvedUsingValueDecl>(Pattern) ||
1128 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1129 "pattern decl is not a using decl");
1130 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1131 InstantiatedFromUsingDecl[Inst] = Pattern;
1132}
1133
1134UsingShadowDecl *
1135ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1136 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1137 = InstantiatedFromUsingShadowDecl.find(Inst);
1138 if (Pos == InstantiatedFromUsingShadowDecl.end())
1139 return 0;
1140
1141 return Pos->second;
1142}
1143
1144void
1145ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1146 UsingShadowDecl *Pattern) {
1147 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1148 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001149}
1150
Anders Carlsson5da84842009-09-01 04:26:58 +00001151FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1152 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1153 = InstantiatedFromUnnamedFieldDecl.find(Field);
1154 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1155 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001156
Anders Carlsson5da84842009-09-01 04:26:58 +00001157 return Pos->second;
1158}
1159
1160void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1161 FieldDecl *Tmpl) {
1162 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1163 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1164 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1165 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001166
Anders Carlsson5da84842009-09-01 04:26:58 +00001167 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1168}
1169
Douglas Gregor832940b2010-03-02 23:58:15 +00001170ASTContext::overridden_cxx_method_iterator
1171ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1172 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001173 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001174 if (Pos == OverriddenMethods.end())
1175 return 0;
1176
1177 return Pos->second.begin();
1178}
1179
1180ASTContext::overridden_cxx_method_iterator
1181ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1182 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001183 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001184 if (Pos == OverriddenMethods.end())
1185 return 0;
1186
1187 return Pos->second.end();
1188}
1189
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001190unsigned
1191ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1192 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001193 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001194 if (Pos == OverriddenMethods.end())
1195 return 0;
1196
1197 return Pos->second.size();
1198}
1199
Douglas Gregor832940b2010-03-02 23:58:15 +00001200void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1201 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001202 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001203 OverriddenMethods[Method].push_back(Overridden);
1204}
1205
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001206void ASTContext::getOverriddenMethods(
1207 const NamedDecl *D,
1208 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001209 assert(D);
1210
1211 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001212 Overridden.append(overridden_methods_begin(CXXMethod),
1213 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001214 return;
1215 }
1216
1217 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1218 if (!Method)
1219 return;
1220
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001221 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1222 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001223 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001224}
1225
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001226void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1227 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1228 assert(!Import->isFromASTFile() && "Non-local import declaration");
1229 if (!FirstLocalImport) {
1230 FirstLocalImport = Import;
1231 LastLocalImport = Import;
1232 return;
1233 }
1234
1235 LastLocalImport->NextLocalImport = Import;
1236 LastLocalImport = Import;
1237}
1238
Chris Lattner53cfe802007-07-18 17:52:12 +00001239//===----------------------------------------------------------------------===//
1240// Type Sizing and Analysis
1241//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001242
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001243/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1244/// scalar floating point type.
1245const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001246 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001247 assert(BT && "Not a floating point type!");
1248 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001249 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001250 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001251 case BuiltinType::Float: return Target->getFloatFormat();
1252 case BuiltinType::Double: return Target->getDoubleFormat();
1253 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001254 }
1255}
1256
Rafael Espindola71eccb32013-08-08 19:53:46 +00001257CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001258 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001259
John McCall94268702010-10-08 18:24:19 +00001260 bool UseAlignAttrOnly = false;
1261 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1262 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001263
John McCall94268702010-10-08 18:24:19 +00001264 // __attribute__((aligned)) can increase or decrease alignment
1265 // *except* on a struct or struct member, where it only increases
1266 // alignment unless 'packed' is also specified.
1267 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001268 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001269 // ignore that possibility; Sema should diagnose it.
1270 if (isa<FieldDecl>(D)) {
1271 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1272 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1273 } else {
1274 UseAlignAttrOnly = true;
1275 }
1276 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001277 else if (isa<FieldDecl>(D))
1278 UseAlignAttrOnly =
1279 D->hasAttr<PackedAttr>() ||
1280 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001281
John McCall4e819612011-01-20 07:57:12 +00001282 // If we're using the align attribute only, just ignore everything
1283 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001284 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001285 // do nothing
1286
John McCall94268702010-10-08 18:24:19 +00001287 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001288 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001289 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001290 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001291 T = RT->getPointeeType();
1292 else
1293 T = getPointerType(RT->getPointeeType());
1294 }
1295 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001296 // Adjust alignments of declarations with array type by the
1297 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001298 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001299 unsigned MinWidth = Target->getLargeArrayMinWidth();
1300 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001301 if (isa<VariableArrayType>(arrayType))
1302 Align = std::max(Align, Target->getLargeArrayAlign());
1303 else if (isa<ConstantArrayType>(arrayType) &&
1304 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1305 Align = std::max(Align, Target->getLargeArrayAlign());
1306 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001307
John McCall33ddac02011-01-19 10:06:00 +00001308 // Walk through any array types while we're at it.
1309 T = getBaseElementType(arrayType);
1310 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001311 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001312 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1313 if (VD->hasGlobalStorage())
1314 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1315 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001316 }
John McCall4e819612011-01-20 07:57:12 +00001317
1318 // Fields can be subject to extra alignment constraints, like if
1319 // the field is packed, the struct is packed, or the struct has a
1320 // a max-field-alignment constraint (#pragma pack). So calculate
1321 // the actual alignment of the field within the struct, and then
1322 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001323 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1324 const RecordDecl *Parent = Field->getParent();
1325 // We can only produce a sensible answer if the record is valid.
1326 if (!Parent->isInvalidDecl()) {
1327 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001328
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001329 // Start with the record's overall alignment.
1330 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001331
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001332 // Use the GCD of that and the offset within the record.
1333 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1334 if (Offset > 0) {
1335 // Alignment is always a power of 2, so the GCD will be a power of 2,
1336 // which means we get to do this crazy thing instead of Euclid's.
1337 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1338 if (LowBitOfOffset < FieldAlign)
1339 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1340 }
1341
1342 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001343 }
Charles Davis3fc51072010-02-23 04:52:00 +00001344 }
Chris Lattner68061312009-01-24 21:53:27 +00001345 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001346
Ken Dyckcc56c542011-01-15 18:38:59 +00001347 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001348}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001349
John McCallf1249922012-08-21 04:10:00 +00001350// getTypeInfoDataSizeInChars - Return the size of a type, in
1351// chars. If the type is a record, its data size is returned. This is
1352// the size of the memcpy that's performed when assigning this type
1353// using a trivial copy/move assignment operator.
1354std::pair<CharUnits, CharUnits>
1355ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1356 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1357
1358 // In C++, objects can sometimes be allocated into the tail padding
1359 // of a base-class subobject. We decide whether that's possible
1360 // during class layout, so here we can just trust the layout results.
1361 if (getLangOpts().CPlusPlus) {
1362 if (const RecordType *RT = T->getAs<RecordType>()) {
1363 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1364 sizeAndAlign.first = layout.getDataSize();
1365 }
1366 }
1367
1368 return sizeAndAlign;
1369}
1370
Richard Trieu04d2d942013-05-14 21:59:17 +00001371/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1372/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1373std::pair<CharUnits, CharUnits>
1374static getConstantArrayInfoInChars(const ASTContext &Context,
1375 const ConstantArrayType *CAT) {
1376 std::pair<CharUnits, CharUnits> EltInfo =
1377 Context.getTypeInfoInChars(CAT->getElementType());
1378 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001379 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1380 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001381 "Overflow in array type char size evaluation");
1382 uint64_t Width = EltInfo.first.getQuantity() * Size;
1383 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001384 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1385 Context.getTargetInfo().getPointerWidth(0) == 64)
1386 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001387 return std::make_pair(CharUnits::fromQuantity(Width),
1388 CharUnits::fromQuantity(Align));
1389}
1390
John McCall87fe5d52010-05-20 01:18:31 +00001391std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001392ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001393 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1394 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001395 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001396 return std::make_pair(toCharUnitsFromBits(Info.first),
1397 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001398}
1399
1400std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001401ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001402 return getTypeInfoInChars(T.getTypePtr());
1403}
1404
Daniel Dunbarc6475872012-03-09 04:12:54 +00001405std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1406 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1407 if (it != MemoizedTypeInfo.end())
1408 return it->second;
1409
1410 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1411 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1412 return Info;
1413}
1414
1415/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1416/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001417///
1418/// FIXME: Pointers into different addr spaces could have different sizes and
1419/// alignment requirements: getPointerInfo should take an AddrSpace, this
1420/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001421std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001422ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001423 uint64_t Width=0;
1424 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001425 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001426#define TYPE(Class, Base)
1427#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001428#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001429#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001430#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1431 case Type::Class: \
1432 assert(!T->isDependentType() && "should not see dependent types here"); \
1433 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001434#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001435 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001436
Chris Lattner355332d2007-07-13 22:27:08 +00001437 case Type::FunctionNoProto:
1438 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001439 // GCC extension: alignof(function) = 32 bits
1440 Width = 0;
1441 Align = 32;
1442 break;
1443
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001444 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001445 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001446 Width = 0;
1447 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1448 break;
1449
Steve Naroff5c131802007-08-30 01:06:46 +00001450 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001451 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Chris Lattner37e05872008-03-05 18:54:05 +00001453 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001454 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001455 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1456 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001457 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001458 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001459 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1460 getTargetInfo().getPointerWidth(0) == 64)
1461 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001462 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001463 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001464 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001465 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001466 const VectorType *VT = cast<VectorType>(T);
1467 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1468 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001469 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001470 // If the alignment is not a power of 2, round up to the next power of 2.
1471 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001472 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001473 Align = llvm::NextPowerOf2(Align);
1474 Width = llvm::RoundUpToAlignment(Width, Align);
1475 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001476 // Adjust the alignment based on the target max.
1477 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1478 if (TargetVectorAlign && TargetVectorAlign < Align)
1479 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001480 break;
1481 }
Chris Lattner647fb222007-07-18 18:26:58 +00001482
Chris Lattner7570e9c2008-03-08 08:52:55 +00001483 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001484 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001485 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001486 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001487 // GCC extension: alignof(void) = 8 bits.
1488 Width = 0;
1489 Align = 8;
1490 break;
1491
Chris Lattner6a4f7452007-12-19 19:23:28 +00001492 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001493 Width = Target->getBoolWidth();
1494 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001495 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001496 case BuiltinType::Char_S:
1497 case BuiltinType::Char_U:
1498 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001500 Width = Target->getCharWidth();
1501 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001502 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001503 case BuiltinType::WChar_S:
1504 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001505 Width = Target->getWCharWidth();
1506 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001507 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001508 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001509 Width = Target->getChar16Width();
1510 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001511 break;
1512 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001513 Width = Target->getChar32Width();
1514 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001515 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001516 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001517 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001518 Width = Target->getShortWidth();
1519 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001520 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001521 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001522 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001523 Width = Target->getIntWidth();
1524 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001525 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001526 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001528 Width = Target->getLongWidth();
1529 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001530 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001531 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001533 Width = Target->getLongLongWidth();
1534 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001535 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001536 case BuiltinType::Int128:
1537 case BuiltinType::UInt128:
1538 Width = 128;
1539 Align = 128; // int128_t is 128-bit aligned on all targets.
1540 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001541 case BuiltinType::Half:
1542 Width = Target->getHalfWidth();
1543 Align = Target->getHalfAlign();
1544 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001545 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001546 Width = Target->getFloatWidth();
1547 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001548 break;
1549 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001550 Width = Target->getDoubleWidth();
1551 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001552 break;
1553 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001554 Width = Target->getLongDoubleWidth();
1555 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001556 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001557 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001558 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1559 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001560 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001561 case BuiltinType::ObjCId:
1562 case BuiltinType::ObjCClass:
1563 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001564 Width = Target->getPointerWidth(0);
1565 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001566 break;
Guy Benyei61054192013-02-07 10:55:47 +00001567 case BuiltinType::OCLSampler:
1568 // Samplers are modeled as integers.
1569 Width = Target->getIntWidth();
1570 Align = Target->getIntAlign();
1571 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001572 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001573 case BuiltinType::OCLImage1d:
1574 case BuiltinType::OCLImage1dArray:
1575 case BuiltinType::OCLImage1dBuffer:
1576 case BuiltinType::OCLImage2d:
1577 case BuiltinType::OCLImage2dArray:
1578 case BuiltinType::OCLImage3d:
1579 // Currently these types are pointers to opaque types.
1580 Width = Target->getPointerWidth(0);
1581 Align = Target->getPointerAlign(0);
1582 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001583 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001584 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001585 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001586 Width = Target->getPointerWidth(0);
1587 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001588 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001589 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001590 unsigned AS = getTargetAddressSpace(
1591 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(AS);
1593 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001594 break;
1595 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001596 case Type::LValueReference:
1597 case Type::RValueReference: {
1598 // alignof and sizeof should never enter this code path here, so we go
1599 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001600 unsigned AS = getTargetAddressSpace(
1601 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001602 Width = Target->getPointerWidth(AS);
1603 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001604 break;
1605 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001606 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001607 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001608 Width = Target->getPointerWidth(AS);
1609 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001610 break;
1611 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001612 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001613 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001614 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001615 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001616 }
Chris Lattner647fb222007-07-18 18:26:58 +00001617 case Type::Complex: {
1618 // Complex types have the same alignment as their elements, but twice the
1619 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001620 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001621 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001622 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001623 Align = EltInfo.second;
1624 break;
1625 }
John McCall8b07ec22010-05-15 11:32:37 +00001626 case Type::ObjCObject:
1627 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001628 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001629 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001630 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001631 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001632 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001633 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001634 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001635 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001636 break;
1637 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001638 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001639 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001640 const TagType *TT = cast<TagType>(T);
1641
1642 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001643 Width = 8;
1644 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001645 break;
1646 }
Mike Stump11289f42009-09-09 15:08:12 +00001647
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001648 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001649 return getTypeInfo(ET->getDecl()->getIntegerType());
1650
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001651 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001652 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001653 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001654 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001655 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001656 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001657
Chris Lattner63d2b362009-10-22 05:17:15 +00001658 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001659 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1660 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001661
Richard Smith30482bc2011-02-20 03:19:35 +00001662 case Type::Auto: {
1663 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001664 assert(!A->getDeducedType().isNull() &&
1665 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001666 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001667 }
1668
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001669 case Type::Paren:
1670 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1671
Douglas Gregoref462e62009-04-30 17:32:17 +00001672 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001673 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001674 std::pair<uint64_t, unsigned> Info
1675 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001676 // If the typedef has an aligned attribute on it, it overrides any computed
1677 // alignment we have. This violates the GCC documentation (which says that
1678 // attribute(aligned) can only round up) but matches its implementation.
1679 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1680 Align = AttrAlign;
1681 else
1682 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001683 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001684 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001685 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001686
Abramo Bagnara6150c882010-05-11 21:36:43 +00001687 case Type::Elaborated:
1688 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001689
John McCall81904512011-01-06 01:58:22 +00001690 case Type::Attributed:
1691 return getTypeInfo(
1692 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1693
Eli Friedman0dfb8892011-10-06 23:00:33 +00001694 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001695 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001696 std::pair<uint64_t, unsigned> Info
1697 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1698 Width = Info.first;
1699 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001700
1701 // If the size of the type doesn't exceed the platform's max
1702 // atomic promotion width, make the size and alignment more
1703 // favorable to atomic operations:
1704 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1705 // Round the size up to a power of 2.
1706 if (!llvm::isPowerOf2_64(Width))
1707 Width = llvm::NextPowerOf2(Width);
1708
1709 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001710 Align = static_cast<unsigned>(Width);
1711 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001712 }
1713
Douglas Gregoref462e62009-04-30 17:32:17 +00001714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001716 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001717 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001718}
1719
Ken Dyckcc56c542011-01-15 18:38:59 +00001720/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1721CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1722 return CharUnits::fromQuantity(BitSize / getCharWidth());
1723}
1724
Ken Dyckb0fcc592011-02-11 01:54:29 +00001725/// toBits - Convert a size in characters to a size in characters.
1726int64_t ASTContext::toBits(CharUnits CharSize) const {
1727 return CharSize.getQuantity() * getCharWidth();
1728}
1729
Ken Dyck8c89d592009-12-22 14:23:30 +00001730/// getTypeSizeInChars - Return the size of the specified type, in characters.
1731/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001732CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001733 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001734}
Jay Foad39c79802011-01-12 09:06:06 +00001735CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001736 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001737}
1738
Ken Dycka6046ab2010-01-26 17:25:18 +00001739/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001740/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001741CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001742 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001743}
Jay Foad39c79802011-01-12 09:06:06 +00001744CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001745 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001746}
1747
Chris Lattnera3402cd2009-01-27 18:08:34 +00001748/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1749/// type for the current target in bits. This can be different than the ABI
1750/// alignment in cases where it is beneficial for performance to overalign
1751/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001752unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001753 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001754
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001755 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1756 return ABIAlign; // Never overalign on XCore.
1757
David Majnemer8b6bd572014-02-24 23:34:17 +00001758 const TypedefType *TT = T->getAs<TypedefType>();
1759
Eli Friedman7ab09572009-05-25 21:27:19 +00001760 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001761 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001762 T = CT->getElementType().getTypePtr();
1763 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001764 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1765 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001766 // Don't increase the alignment if an alignment attribute was specified on a
1767 // typedef declaration.
1768 if (!TT || !TT->getDecl()->getMaxAlignment())
1769 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001770
Chris Lattnera3402cd2009-01-27 18:08:34 +00001771 return ABIAlign;
1772}
1773
Ulrich Weigandfa806422013-05-06 16:23:57 +00001774/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1775/// to a global variable of the specified type.
1776unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1777 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1778}
1779
1780/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1781/// should be given to a global variable of the specified type.
1782CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1783 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1784}
1785
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001786/// DeepCollectObjCIvars -
1787/// This routine first collects all declared, but not synthesized, ivars in
1788/// super class and then collects all ivars, including those synthesized for
1789/// current class. This routine is used for implementation of current class
1790/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001791///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001792void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1793 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001794 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001795 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1796 DeepCollectObjCIvars(SuperClass, false, Ivars);
1797 if (!leafClass) {
1798 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1799 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001800 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001801 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001802 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001803 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001804 Iv= Iv->getNextIvar())
1805 Ivars.push_back(Iv);
1806 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001807}
1808
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001809/// CollectInheritedProtocols - Collect all protocols in current class and
1810/// those inherited by it.
1811void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001812 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001813 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001814 // We can use protocol_iterator here instead of
1815 // all_referenced_protocol_iterator since we are walking all categories.
1816 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1817 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001818 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001819 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001820 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001821 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001822 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001823 CollectInheritedProtocols(*P, Protocols);
1824 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001825 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001826
1827 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001828 for (ObjCInterfaceDecl::visible_categories_iterator
1829 Cat = OI->visible_categories_begin(),
1830 CatEnd = OI->visible_categories_end();
1831 Cat != CatEnd; ++Cat) {
1832 CollectInheritedProtocols(*Cat, Protocols);
1833 }
1834
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001835 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1836 while (SD) {
1837 CollectInheritedProtocols(SD, Protocols);
1838 SD = SD->getSuperClass();
1839 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001840 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001841 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001842 PE = OC->protocol_end(); P != PE; ++P) {
1843 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001844 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001845 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1846 PE = Proto->protocol_end(); P != PE; ++P)
1847 CollectInheritedProtocols(*P, Protocols);
1848 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001849 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001850 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1851 PE = OP->protocol_end(); P != PE; ++P) {
1852 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001853 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001854 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1855 PE = Proto->protocol_end(); P != PE; ++P)
1856 CollectInheritedProtocols(*P, Protocols);
1857 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001858 }
1859}
1860
Jay Foad39c79802011-01-12 09:06:06 +00001861unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001862 unsigned count = 0;
1863 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001864 for (ObjCInterfaceDecl::known_extensions_iterator
1865 Ext = OI->known_extensions_begin(),
1866 ExtEnd = OI->known_extensions_end();
1867 Ext != ExtEnd; ++Ext) {
1868 count += Ext->ivar_size();
1869 }
1870
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001871 // Count ivar defined in this class's implementation. This
1872 // includes synthesized ivars.
1873 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001874 count += ImplDecl->ivar_size();
1875
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001876 return count;
1877}
1878
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001879bool ASTContext::isSentinelNullExpr(const Expr *E) {
1880 if (!E)
1881 return false;
1882
1883 // nullptr_t is always treated as null.
1884 if (E->getType()->isNullPtrType()) return true;
1885
1886 if (E->getType()->isAnyPointerType() &&
1887 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1888 Expr::NPC_ValueDependentIsNull))
1889 return true;
1890
1891 // Unfortunately, __null has type 'int'.
1892 if (isa<GNUNullExpr>(E)) return true;
1893
1894 return false;
1895}
1896
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001897/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1898ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1899 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1900 I = ObjCImpls.find(D);
1901 if (I != ObjCImpls.end())
1902 return cast<ObjCImplementationDecl>(I->second);
1903 return 0;
1904}
1905/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1906ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1907 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1908 I = ObjCImpls.find(D);
1909 if (I != ObjCImpls.end())
1910 return cast<ObjCCategoryImplDecl>(I->second);
1911 return 0;
1912}
1913
1914/// \brief Set the implementation of ObjCInterfaceDecl.
1915void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1916 ObjCImplementationDecl *ImplD) {
1917 assert(IFaceD && ImplD && "Passed null params");
1918 ObjCImpls[IFaceD] = ImplD;
1919}
1920/// \brief Set the implementation of ObjCCategoryDecl.
1921void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1922 ObjCCategoryImplDecl *ImplD) {
1923 assert(CatD && ImplD && "Passed null params");
1924 ObjCImpls[CatD] = ImplD;
1925}
1926
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001927const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1928 const NamedDecl *ND) const {
1929 if (const ObjCInterfaceDecl *ID =
1930 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001931 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001932 if (const ObjCCategoryDecl *CD =
1933 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001934 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001935 if (const ObjCImplDecl *IMD =
1936 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001937 return IMD->getClassInterface();
1938
1939 return 0;
1940}
1941
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001942/// \brief Get the copy initialization expression of VarDecl,or NULL if
1943/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001944Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001945 assert(VD && "Passed null params");
1946 assert(VD->hasAttr<BlocksAttr>() &&
1947 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001948 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001949 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001950 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1951}
1952
1953/// \brief Set the copy inialization expression of a block var decl.
1954void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1955 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001956 assert(VD->hasAttr<BlocksAttr>() &&
1957 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001958 BlockVarCopyInits[VD] = Init;
1959}
1960
John McCallbcd03502009-12-07 02:54:59 +00001961TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001962 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001963 if (!DataSize)
1964 DataSize = TypeLoc::getFullDataSizeForType(T);
1965 else
1966 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001967 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001968
John McCallbcd03502009-12-07 02:54:59 +00001969 TypeSourceInfo *TInfo =
1970 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1971 new (TInfo) TypeSourceInfo(T);
1972 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001973}
1974
John McCallbcd03502009-12-07 02:54:59 +00001975TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001976 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001977 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001978 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001979 return DI;
1980}
1981
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001982const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001983ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001984 return getObjCLayout(D, 0);
1985}
1986
1987const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001988ASTContext::getASTObjCImplementationLayout(
1989 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001990 return getObjCLayout(D->getClassInterface(), D);
1991}
1992
Chris Lattner983a8bb2007-07-13 22:13:22 +00001993//===----------------------------------------------------------------------===//
1994// Type creation/memoization methods
1995//===----------------------------------------------------------------------===//
1996
Jay Foad39c79802011-01-12 09:06:06 +00001997QualType
John McCall33ddac02011-01-19 10:06:00 +00001998ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1999 unsigned fastQuals = quals.getFastQualifiers();
2000 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002001
2002 // Check if we've already instantiated this type.
2003 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002004 ExtQuals::Profile(ID, baseType, quals);
2005 void *insertPos = 0;
2006 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2007 assert(eq->getQualifiers() == quals);
2008 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002009 }
2010
John McCall33ddac02011-01-19 10:06:00 +00002011 // If the base type is not canonical, make the appropriate canonical type.
2012 QualType canon;
2013 if (!baseType->isCanonicalUnqualified()) {
2014 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002015 canonSplit.Quals.addConsistentQualifiers(quals);
2016 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002017
2018 // Re-find the insert position.
2019 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2020 }
2021
2022 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2023 ExtQualNodes.InsertNode(eq, insertPos);
2024 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002025}
2026
Jay Foad39c79802011-01-12 09:06:06 +00002027QualType
2028ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002029 QualType CanT = getCanonicalType(T);
2030 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002031 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002032
John McCall8ccfcb52009-09-24 19:53:00 +00002033 // If we are composing extended qualifiers together, merge together
2034 // into one ExtQuals node.
2035 QualifierCollector Quals;
2036 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002037
John McCall8ccfcb52009-09-24 19:53:00 +00002038 // If this type already has an address space specified, it cannot get
2039 // another one.
2040 assert(!Quals.hasAddressSpace() &&
2041 "Type cannot be in multiple addr spaces!");
2042 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002043
John McCall8ccfcb52009-09-24 19:53:00 +00002044 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002045}
2046
Chris Lattnerd60183d2009-02-18 22:53:11 +00002047QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002048 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002049 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002050 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002051 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002052
John McCall53fa7142010-12-24 02:08:15 +00002053 if (const PointerType *ptr = T->getAs<PointerType>()) {
2054 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002055 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002056 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2057 return getPointerType(ResultType);
2058 }
2059 }
Mike Stump11289f42009-09-09 15:08:12 +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 ObjCGC specified, it cannot get
2067 // another one.
2068 assert(!Quals.hasObjCGCAttr() &&
2069 "Type cannot have multiple ObjCGCs!");
2070 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002071
John McCall8ccfcb52009-09-24 19:53:00 +00002072 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002073}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002074
John McCall4f5019e2010-12-19 02:44:49 +00002075const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2076 FunctionType::ExtInfo Info) {
2077 if (T->getExtInfo() == Info)
2078 return T;
2079
2080 QualType Result;
2081 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002082 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002083 } else {
2084 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2085 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2086 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002087 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002088 }
2089
2090 return cast<FunctionType>(Result.getTypePtr());
2091}
2092
Richard Smith2a7d4812013-05-04 07:00:32 +00002093void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2094 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002095 FD = FD->getMostRecentDecl();
2096 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002097 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2098 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002099 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002100 if (FunctionDecl *Next = FD->getPreviousDecl())
2101 FD = Next;
2102 else
2103 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002104 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002105 if (ASTMutationListener *L = getASTMutationListener())
2106 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002107}
2108
Chris Lattnerc6395932007-06-22 20:56:16 +00002109/// getComplexType - Return the uniqued reference to the type for a complex
2110/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002111QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002112 // Unique pointers, to guarantee there is only one pointer of a particular
2113 // structure.
2114 llvm::FoldingSetNodeID ID;
2115 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002116
Chris Lattnerc6395932007-06-22 20:56:16 +00002117 void *InsertPos = 0;
2118 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2119 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002120
Chris Lattnerc6395932007-06-22 20:56:16 +00002121 // If the pointee type isn't canonical, this won't be a canonical type either,
2122 // so fill in the canonical type field.
2123 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002124 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002125 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002126
Chris Lattnerc6395932007-06-22 20:56:16 +00002127 // Get the new insert position for the node we care about.
2128 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002129 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002130 }
John McCall90d1c2d2009-09-24 23:30:46 +00002131 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002132 Types.push_back(New);
2133 ComplexTypes.InsertNode(New, InsertPos);
2134 return QualType(New, 0);
2135}
2136
Chris Lattner970e54e2006-11-12 00:37:36 +00002137/// getPointerType - Return the uniqued reference to the type for a pointer to
2138/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002139QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002140 // Unique pointers, to guarantee there is only one pointer of a particular
2141 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002142 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002143 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002144
Chris Lattner67521df2007-01-27 01:29:36 +00002145 void *InsertPos = 0;
2146 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002147 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002148
Chris Lattner7ccecb92006-11-12 08:50:50 +00002149 // If the pointee type isn't canonical, this won't be a canonical type either,
2150 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002151 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002152 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002153 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002154
Bob Wilsonc8541f22013-03-15 17:12:43 +00002155 // Get the new insert position for the node we care about.
2156 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2157 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2158 }
John McCall90d1c2d2009-09-24 23:30:46 +00002159 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002160 Types.push_back(New);
2161 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002162 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002163}
2164
Reid Kleckner0503a872013-12-05 01:23:43 +00002165QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2166 llvm::FoldingSetNodeID ID;
2167 AdjustedType::Profile(ID, Orig, New);
2168 void *InsertPos = 0;
2169 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2170 if (AT)
2171 return QualType(AT, 0);
2172
2173 QualType Canonical = getCanonicalType(New);
2174
2175 // Get the new insert position for the node we care about.
2176 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2177 assert(AT == 0 && "Shouldn't be in the map!");
2178
2179 AT = new (*this, TypeAlignment)
2180 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2181 Types.push_back(AT);
2182 AdjustedTypes.InsertNode(AT, InsertPos);
2183 return QualType(AT, 0);
2184}
2185
Reid Kleckner8a365022013-06-24 17:51:48 +00002186QualType ASTContext::getDecayedType(QualType T) const {
2187 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2188
Reid Kleckner8a365022013-06-24 17:51:48 +00002189 QualType Decayed;
2190
2191 // C99 6.7.5.3p7:
2192 // A declaration of a parameter as "array of type" shall be
2193 // adjusted to "qualified pointer to type", where the type
2194 // qualifiers (if any) are those specified within the [ and ] of
2195 // the array type derivation.
2196 if (T->isArrayType())
2197 Decayed = getArrayDecayedType(T);
2198
2199 // C99 6.7.5.3p8:
2200 // A declaration of a parameter as "function returning type"
2201 // shall be adjusted to "pointer to function returning type", as
2202 // in 6.3.2.1.
2203 if (T->isFunctionType())
2204 Decayed = getPointerType(T);
2205
Reid Kleckner0503a872013-12-05 01:23:43 +00002206 llvm::FoldingSetNodeID ID;
2207 AdjustedType::Profile(ID, T, Decayed);
2208 void *InsertPos = 0;
2209 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2210 if (AT)
2211 return QualType(AT, 0);
2212
Reid Kleckner8a365022013-06-24 17:51:48 +00002213 QualType Canonical = getCanonicalType(Decayed);
2214
2215 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002216 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2217 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002218
Reid Kleckner0503a872013-12-05 01:23:43 +00002219 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2220 Types.push_back(AT);
2221 AdjustedTypes.InsertNode(AT, InsertPos);
2222 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002223}
2224
Mike Stump11289f42009-09-09 15:08:12 +00002225/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002226/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002227QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002228 assert(T->isFunctionType() && "block of function types only");
2229 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002230 // structure.
2231 llvm::FoldingSetNodeID ID;
2232 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002233
Steve Naroffec33ed92008-08-27 16:04:49 +00002234 void *InsertPos = 0;
2235 if (BlockPointerType *PT =
2236 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2237 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002238
2239 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002240 // type either so fill in the canonical type field.
2241 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002242 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002243 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002244
Steve Naroffec33ed92008-08-27 16:04:49 +00002245 // Get the new insert position for the node we care about.
2246 BlockPointerType *NewIP =
2247 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002248 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002249 }
John McCall90d1c2d2009-09-24 23:30:46 +00002250 BlockPointerType *New
2251 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002252 Types.push_back(New);
2253 BlockPointerTypes.InsertNode(New, InsertPos);
2254 return QualType(New, 0);
2255}
2256
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002257/// getLValueReferenceType - Return the uniqued reference to the type for an
2258/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002259QualType
2260ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002261 assert(getCanonicalType(T) != OverloadTy &&
2262 "Unresolved overloaded function type");
2263
Bill Wendling3708c182007-05-27 10:15:43 +00002264 // Unique pointers, to guarantee there is only one pointer of a particular
2265 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002266 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002267 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002268
2269 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002270 if (LValueReferenceType *RT =
2271 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002272 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002273
John McCallfc93cf92009-10-22 22:37:11 +00002274 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2275
Bill Wendling3708c182007-05-27 10:15:43 +00002276 // If the referencee type isn't canonical, this won't be a canonical type
2277 // either, so fill in the canonical type field.
2278 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002279 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2280 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2281 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002282
Bill Wendling3708c182007-05-27 10:15:43 +00002283 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002284 LValueReferenceType *NewIP =
2285 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002286 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002287 }
2288
John McCall90d1c2d2009-09-24 23:30:46 +00002289 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002290 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2291 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002292 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002293 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002294
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002295 return QualType(New, 0);
2296}
2297
2298/// getRValueReferenceType - Return the uniqued reference to the type for an
2299/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002300QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002301 // Unique pointers, to guarantee there is only one pointer of a particular
2302 // structure.
2303 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002304 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002305
2306 void *InsertPos = 0;
2307 if (RValueReferenceType *RT =
2308 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2309 return QualType(RT, 0);
2310
John McCallfc93cf92009-10-22 22:37:11 +00002311 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2312
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002313 // If the referencee type isn't canonical, this won't be a canonical type
2314 // either, so fill in the canonical type field.
2315 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002316 if (InnerRef || !T.isCanonical()) {
2317 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2318 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002319
2320 // Get the new insert position for the node we care about.
2321 RValueReferenceType *NewIP =
2322 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002323 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002324 }
2325
John McCall90d1c2d2009-09-24 23:30:46 +00002326 RValueReferenceType *New
2327 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002328 Types.push_back(New);
2329 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002330 return QualType(New, 0);
2331}
2332
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002333/// getMemberPointerType - Return the uniqued reference to the type for a
2334/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002335QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002336 // Unique pointers, to guarantee there is only one pointer of a particular
2337 // structure.
2338 llvm::FoldingSetNodeID ID;
2339 MemberPointerType::Profile(ID, T, Cls);
2340
2341 void *InsertPos = 0;
2342 if (MemberPointerType *PT =
2343 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2344 return QualType(PT, 0);
2345
2346 // If the pointee or class type isn't canonical, this won't be a canonical
2347 // type either, so fill in the canonical type field.
2348 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002349 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002350 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2351
2352 // Get the new insert position for the node we care about.
2353 MemberPointerType *NewIP =
2354 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002355 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002356 }
John McCall90d1c2d2009-09-24 23:30:46 +00002357 MemberPointerType *New
2358 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002359 Types.push_back(New);
2360 MemberPointerTypes.InsertNode(New, InsertPos);
2361 return QualType(New, 0);
2362}
2363
Mike Stump11289f42009-09-09 15:08:12 +00002364/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002365/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002366QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002367 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002368 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002369 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002370 assert((EltTy->isDependentType() ||
2371 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002372 "Constant array of VLAs is illegal!");
2373
Chris Lattnere2df3f92009-05-13 04:12:56 +00002374 // Convert the array size into a canonical width matching the pointer size for
2375 // the target.
2376 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002377 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002378 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002379
Chris Lattner23b7eb62007-06-15 23:05:46 +00002380 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002381 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002382
Chris Lattner36f8e652007-01-27 08:31:04 +00002383 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002384 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002385 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002386 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002387
John McCall33ddac02011-01-19 10:06:00 +00002388 // If the element type isn't canonical or has qualifiers, this won't
2389 // be a canonical type either, so fill in the canonical type field.
2390 QualType Canon;
2391 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2392 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002393 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002394 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002395 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002396
Chris Lattner36f8e652007-01-27 08:31:04 +00002397 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002398 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002399 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002400 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002401 }
Mike Stump11289f42009-09-09 15:08:12 +00002402
John McCall90d1c2d2009-09-24 23:30:46 +00002403 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002404 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002405 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002406 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002407 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002408}
2409
John McCall06549462011-01-18 08:40:38 +00002410/// getVariableArrayDecayedType - Turns the given type, which may be
2411/// variably-modified, into the corresponding type with all the known
2412/// sizes replaced with [*].
2413QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2414 // Vastly most common case.
2415 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002416
John McCall06549462011-01-18 08:40:38 +00002417 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002418
John McCall06549462011-01-18 08:40:38 +00002419 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002420 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002421 switch (ty->getTypeClass()) {
2422#define TYPE(Class, Base)
2423#define ABSTRACT_TYPE(Class, Base)
2424#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2425#include "clang/AST/TypeNodes.def"
2426 llvm_unreachable("didn't desugar past all non-canonical types?");
2427
2428 // These types should never be variably-modified.
2429 case Type::Builtin:
2430 case Type::Complex:
2431 case Type::Vector:
2432 case Type::ExtVector:
2433 case Type::DependentSizedExtVector:
2434 case Type::ObjCObject:
2435 case Type::ObjCInterface:
2436 case Type::ObjCObjectPointer:
2437 case Type::Record:
2438 case Type::Enum:
2439 case Type::UnresolvedUsing:
2440 case Type::TypeOfExpr:
2441 case Type::TypeOf:
2442 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002443 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002444 case Type::DependentName:
2445 case Type::InjectedClassName:
2446 case Type::TemplateSpecialization:
2447 case Type::DependentTemplateSpecialization:
2448 case Type::TemplateTypeParm:
2449 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002450 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002451 case Type::PackExpansion:
2452 llvm_unreachable("type should never be variably-modified");
2453
2454 // These types can be variably-modified but should never need to
2455 // further decay.
2456 case Type::FunctionNoProto:
2457 case Type::FunctionProto:
2458 case Type::BlockPointer:
2459 case Type::MemberPointer:
2460 return type;
2461
2462 // These types can be variably-modified. All these modifications
2463 // preserve structure except as noted by comments.
2464 // TODO: if we ever care about optimizing VLAs, there are no-op
2465 // optimizations available here.
2466 case Type::Pointer:
2467 result = getPointerType(getVariableArrayDecayedType(
2468 cast<PointerType>(ty)->getPointeeType()));
2469 break;
2470
2471 case Type::LValueReference: {
2472 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2473 result = getLValueReferenceType(
2474 getVariableArrayDecayedType(lv->getPointeeType()),
2475 lv->isSpelledAsLValue());
2476 break;
2477 }
2478
2479 case Type::RValueReference: {
2480 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2481 result = getRValueReferenceType(
2482 getVariableArrayDecayedType(lv->getPointeeType()));
2483 break;
2484 }
2485
Eli Friedman0dfb8892011-10-06 23:00:33 +00002486 case Type::Atomic: {
2487 const AtomicType *at = cast<AtomicType>(ty);
2488 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2489 break;
2490 }
2491
John McCall06549462011-01-18 08:40:38 +00002492 case Type::ConstantArray: {
2493 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2494 result = getConstantArrayType(
2495 getVariableArrayDecayedType(cat->getElementType()),
2496 cat->getSize(),
2497 cat->getSizeModifier(),
2498 cat->getIndexTypeCVRQualifiers());
2499 break;
2500 }
2501
2502 case Type::DependentSizedArray: {
2503 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2504 result = getDependentSizedArrayType(
2505 getVariableArrayDecayedType(dat->getElementType()),
2506 dat->getSizeExpr(),
2507 dat->getSizeModifier(),
2508 dat->getIndexTypeCVRQualifiers(),
2509 dat->getBracketsRange());
2510 break;
2511 }
2512
2513 // Turn incomplete types into [*] types.
2514 case Type::IncompleteArray: {
2515 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2516 result = getVariableArrayType(
2517 getVariableArrayDecayedType(iat->getElementType()),
2518 /*size*/ 0,
2519 ArrayType::Normal,
2520 iat->getIndexTypeCVRQualifiers(),
2521 SourceRange());
2522 break;
2523 }
2524
2525 // Turn VLA types into [*] types.
2526 case Type::VariableArray: {
2527 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2528 result = getVariableArrayType(
2529 getVariableArrayDecayedType(vat->getElementType()),
2530 /*size*/ 0,
2531 ArrayType::Star,
2532 vat->getIndexTypeCVRQualifiers(),
2533 vat->getBracketsRange());
2534 break;
2535 }
2536 }
2537
2538 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002539 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002540}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002541
Steve Naroffcadebd02007-08-30 18:14:25 +00002542/// getVariableArrayType - Returns a non-unique reference to the type for a
2543/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002544QualType ASTContext::getVariableArrayType(QualType EltTy,
2545 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002546 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002547 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002548 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002549 // Since we don't unique expressions, it isn't possible to unique VLA's
2550 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002551 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002552
John McCall33ddac02011-01-19 10:06:00 +00002553 // Be sure to pull qualifiers off the element type.
2554 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2555 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002556 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002557 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002558 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002559 }
2560
John McCall90d1c2d2009-09-24 23:30:46 +00002561 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002562 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002563
2564 VariableArrayTypes.push_back(New);
2565 Types.push_back(New);
2566 return QualType(New, 0);
2567}
2568
Douglas Gregor4619e432008-12-05 23:32:09 +00002569/// getDependentSizedArrayType - Returns a non-unique reference to
2570/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002571/// type.
John McCall33ddac02011-01-19 10:06:00 +00002572QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2573 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002574 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002575 unsigned elementTypeQuals,
2576 SourceRange brackets) const {
2577 assert((!numElements || numElements->isTypeDependent() ||
2578 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002579 "Size must be type- or value-dependent!");
2580
John McCall33ddac02011-01-19 10:06:00 +00002581 // Dependently-sized array types that do not have a specified number
2582 // of elements will have their sizes deduced from a dependent
2583 // initializer. We do no canonicalization here at all, which is okay
2584 // because they can't be used in most locations.
2585 if (!numElements) {
2586 DependentSizedArrayType *newType
2587 = new (*this, TypeAlignment)
2588 DependentSizedArrayType(*this, elementType, QualType(),
2589 numElements, ASM, elementTypeQuals,
2590 brackets);
2591 Types.push_back(newType);
2592 return QualType(newType, 0);
2593 }
2594
2595 // Otherwise, we actually build a new type every time, but we
2596 // also build a canonical type.
2597
2598 SplitQualType canonElementType = getCanonicalType(elementType).split();
2599
2600 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002601 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002602 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002603 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002604 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002605
John McCall33ddac02011-01-19 10:06:00 +00002606 // Look for an existing type with these properties.
2607 DependentSizedArrayType *canonTy =
2608 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002609
John McCall33ddac02011-01-19 10:06:00 +00002610 // If we don't have one, build one.
2611 if (!canonTy) {
2612 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002613 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002614 QualType(), numElements, ASM, elementTypeQuals,
2615 brackets);
2616 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2617 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002618 }
2619
John McCall33ddac02011-01-19 10:06:00 +00002620 // Apply qualifiers from the element type to the array.
2621 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002622 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002623
John McCall33ddac02011-01-19 10:06:00 +00002624 // If we didn't need extra canonicalization for the element type,
2625 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002626 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002627 return canon;
2628
2629 // Otherwise, we need to build a type which follows the spelling
2630 // of the element type.
2631 DependentSizedArrayType *sugaredType
2632 = new (*this, TypeAlignment)
2633 DependentSizedArrayType(*this, elementType, canon, numElements,
2634 ASM, elementTypeQuals, brackets);
2635 Types.push_back(sugaredType);
2636 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002637}
2638
John McCall33ddac02011-01-19 10:06:00 +00002639QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002640 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002641 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002642 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002643 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002644
John McCall33ddac02011-01-19 10:06:00 +00002645 void *insertPos = 0;
2646 if (IncompleteArrayType *iat =
2647 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2648 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002649
2650 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002651 // either, so fill in the canonical type field. We also have to pull
2652 // qualifiers off the element type.
2653 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002654
John McCall33ddac02011-01-19 10:06:00 +00002655 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2656 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002657 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002658 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002659 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002660
2661 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002662 IncompleteArrayType *existing =
2663 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2664 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002665 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002666
John McCall33ddac02011-01-19 10:06:00 +00002667 IncompleteArrayType *newType = new (*this, TypeAlignment)
2668 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002669
John McCall33ddac02011-01-19 10:06:00 +00002670 IncompleteArrayTypes.InsertNode(newType, insertPos);
2671 Types.push_back(newType);
2672 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002673}
2674
Steve Naroff91fcddb2007-07-18 18:00:27 +00002675/// getVectorType - Return the unique reference to a vector type of
2676/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002677QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002678 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002679 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002680
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002681 // Check if we've already instantiated a vector of this type.
2682 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002683 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002684
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002685 void *InsertPos = 0;
2686 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2687 return QualType(VTP, 0);
2688
2689 // If the element type isn't canonical, this won't be a canonical type either,
2690 // so fill in the canonical type field.
2691 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002692 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002693 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002694
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002695 // Get the new insert position for the node we care about.
2696 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002697 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002698 }
John McCall90d1c2d2009-09-24 23:30:46 +00002699 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002700 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002701 VectorTypes.InsertNode(New, InsertPos);
2702 Types.push_back(New);
2703 return QualType(New, 0);
2704}
2705
Nate Begemance4d7fc2008-04-18 23:10:10 +00002706/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002707/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002708QualType
2709ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002710 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002711
Steve Naroff91fcddb2007-07-18 18:00:27 +00002712 // Check if we've already instantiated a vector of this type.
2713 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002714 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002715 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002716 void *InsertPos = 0;
2717 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2718 return QualType(VTP, 0);
2719
2720 // If the element type isn't canonical, this won't be a canonical type either,
2721 // so fill in the canonical type field.
2722 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002723 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002724 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002725
Steve Naroff91fcddb2007-07-18 18:00:27 +00002726 // Get the new insert position for the node we care about.
2727 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002728 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002729 }
John McCall90d1c2d2009-09-24 23:30:46 +00002730 ExtVectorType *New = new (*this, TypeAlignment)
2731 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002732 VectorTypes.InsertNode(New, InsertPos);
2733 Types.push_back(New);
2734 return QualType(New, 0);
2735}
2736
Jay Foad39c79802011-01-12 09:06:06 +00002737QualType
2738ASTContext::getDependentSizedExtVectorType(QualType vecType,
2739 Expr *SizeExpr,
2740 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002741 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002742 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002743 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002744
Douglas Gregor352169a2009-07-31 03:54:25 +00002745 void *InsertPos = 0;
2746 DependentSizedExtVectorType *Canon
2747 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2748 DependentSizedExtVectorType *New;
2749 if (Canon) {
2750 // We already have a canonical version of this array type; use it as
2751 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002752 New = new (*this, TypeAlignment)
2753 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2754 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002755 } else {
2756 QualType CanonVecTy = getCanonicalType(vecType);
2757 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002758 New = new (*this, TypeAlignment)
2759 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2760 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002761
2762 DependentSizedExtVectorType *CanonCheck
2763 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2764 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2765 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002766 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2767 } else {
2768 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2769 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002770 New = new (*this, TypeAlignment)
2771 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002772 }
2773 }
Mike Stump11289f42009-09-09 15:08:12 +00002774
Douglas Gregor758a8692009-06-17 21:51:59 +00002775 Types.push_back(New);
2776 return QualType(New, 0);
2777}
2778
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002779/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002780///
Jay Foad39c79802011-01-12 09:06:06 +00002781QualType
2782ASTContext::getFunctionNoProtoType(QualType ResultTy,
2783 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002784 const CallingConv CallConv = Info.getCC();
2785
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002786 // Unique functions, to guarantee there is only one function of a particular
2787 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002788 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002789 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002790
Chris Lattner47955de2007-01-27 08:37:20 +00002791 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002792 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002793 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002794 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002795
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002796 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002797 if (!ResultTy.isCanonical()) {
2798 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Chris Lattner47955de2007-01-27 08:37:20 +00002800 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002801 FunctionNoProtoType *NewIP =
2802 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002803 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002804 }
Mike Stump11289f42009-09-09 15:08:12 +00002805
Roman Divacky65b88cd2011-03-01 17:40:53 +00002806 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002807 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002808 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002809 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002810 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002811 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002812}
2813
Douglas Gregorcd780372013-01-17 23:36:45 +00002814/// \brief Determine whether \p T is canonical as the result type of a function.
2815static bool isCanonicalResultType(QualType T) {
2816 return T.isCanonical() &&
2817 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2818 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2819}
2820
Jay Foad39c79802011-01-12 09:06:06 +00002821QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002822ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002823 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002824 size_t NumArgs = ArgArray.size();
2825
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002826 // Unique functions, to guarantee there is only one function of a particular
2827 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002828 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002829 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2830 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002831
2832 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002833 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002834 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002835 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002836
2837 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002838 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002839 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002840 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002841 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002842 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002843 isCanonical = false;
2844
2845 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002846 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002847 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002848 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002849 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002850 CanonicalArgs.reserve(NumArgs);
2851 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002852 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002853
John McCalldb40c7f2010-12-14 08:05:40 +00002854 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002855 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002856 CanonicalEPI.ExceptionSpecType = EST_None;
2857 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002858
Douglas Gregorcd780372013-01-17 23:36:45 +00002859 // Result types do not have ARC lifetime qualifiers.
2860 QualType CanResultTy = getCanonicalType(ResultTy);
2861 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2862 Qualifiers Qs = CanResultTy.getQualifiers();
2863 Qs.removeObjCLifetime();
2864 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2865 }
2866
Jordan Rose5c382722013-03-08 21:51:21 +00002867 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002868
Chris Lattnerfd4de792007-01-27 01:15:32 +00002869 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002870 FunctionProtoType *NewIP =
2871 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002872 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002873 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002874
John McCall31168b02011-06-15 23:02:42 +00002875 // FunctionProtoType objects are allocated with extra bytes after
2876 // them for three variable size arrays at the end:
2877 // - parameter types
2878 // - exception types
2879 // - consumed-arguments flags
2880 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002881 // expression, or information used to resolve the exception
2882 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002883 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002884 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002885 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002886 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002887 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002888 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002889 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002890 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002891 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2892 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002893 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002894 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002895 Size += NumArgs * sizeof(bool);
2896
John McCalldb40c7f2010-12-14 08:05:40 +00002897 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002898 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002899 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002900 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002901 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002902 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002903}
Chris Lattneref51c202006-11-10 07:17:23 +00002904
John McCalle78aac42010-03-10 03:28:59 +00002905#ifndef NDEBUG
2906static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2907 if (!isa<CXXRecordDecl>(D)) return false;
2908 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2909 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2910 return true;
2911 if (RD->getDescribedClassTemplate() &&
2912 !isa<ClassTemplateSpecializationDecl>(RD))
2913 return true;
2914 return false;
2915}
2916#endif
2917
2918/// getInjectedClassNameType - Return the unique reference to the
2919/// injected class name type for the specified templated declaration.
2920QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002921 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002922 assert(NeedsInjectedClassNameType(Decl));
2923 if (Decl->TypeForDecl) {
2924 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002925 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002926 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2927 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2928 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2929 } else {
John McCall424cec92011-01-19 06:33:43 +00002930 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002931 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002932 Decl->TypeForDecl = newType;
2933 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002934 }
2935 return QualType(Decl->TypeForDecl, 0);
2936}
2937
Douglas Gregor83a586e2008-04-13 21:07:44 +00002938/// getTypeDeclType - Return the unique reference to the type for the
2939/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002940QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002941 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002942 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002943
Richard Smithdda56e42011-04-15 14:24:37 +00002944 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002945 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002946
John McCall96f0b5f2010-03-10 06:48:02 +00002947 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2948 "Template type parameter types are always available.");
2949
John McCall81e38502010-02-16 03:57:14 +00002950 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002951 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002952 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002953 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002954 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002955 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002956 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002957 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002958 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002959 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2960 Decl->TypeForDecl = newType;
2961 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002962 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002963 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002964
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002965 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002966}
2967
Chris Lattner32d920b2007-01-26 02:01:53 +00002968/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002969/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002970QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002971ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2972 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002973 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002974
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002975 if (Canonical.isNull())
2976 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002977 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002978 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002979 Decl->TypeForDecl = newType;
2980 Types.push_back(newType);
2981 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002982}
2983
Jay Foad39c79802011-01-12 09:06:06 +00002984QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002985 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2986
Douglas Gregorec9fd132012-01-14 16:38:05 +00002987 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002988 if (PrevDecl->TypeForDecl)
2989 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2990
John McCall424cec92011-01-19 06:33:43 +00002991 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2992 Decl->TypeForDecl = newType;
2993 Types.push_back(newType);
2994 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002995}
2996
Jay Foad39c79802011-01-12 09:06:06 +00002997QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002998 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2999
Douglas Gregorec9fd132012-01-14 16:38:05 +00003000 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003001 if (PrevDecl->TypeForDecl)
3002 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3003
John McCall424cec92011-01-19 06:33:43 +00003004 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3005 Decl->TypeForDecl = newType;
3006 Types.push_back(newType);
3007 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003008}
3009
John McCall81904512011-01-06 01:58:22 +00003010QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3011 QualType modifiedType,
3012 QualType equivalentType) {
3013 llvm::FoldingSetNodeID id;
3014 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3015
3016 void *insertPos = 0;
3017 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3018 if (type) return QualType(type, 0);
3019
3020 QualType canon = getCanonicalType(equivalentType);
3021 type = new (*this, TypeAlignment)
3022 AttributedType(canon, attrKind, modifiedType, equivalentType);
3023
3024 Types.push_back(type);
3025 AttributedTypes.InsertNode(type, insertPos);
3026
3027 return QualType(type, 0);
3028}
3029
3030
John McCallcebee162009-10-18 09:09:24 +00003031/// \brief Retrieve a substitution-result type.
3032QualType
3033ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003034 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003035 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003036 && "replacement types must always be canonical");
3037
3038 llvm::FoldingSetNodeID ID;
3039 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3040 void *InsertPos = 0;
3041 SubstTemplateTypeParmType *SubstParm
3042 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3043
3044 if (!SubstParm) {
3045 SubstParm = new (*this, TypeAlignment)
3046 SubstTemplateTypeParmType(Parm, Replacement);
3047 Types.push_back(SubstParm);
3048 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3049 }
3050
3051 return QualType(SubstParm, 0);
3052}
3053
Douglas Gregorada4b792011-01-14 02:55:32 +00003054/// \brief Retrieve a
3055QualType ASTContext::getSubstTemplateTypeParmPackType(
3056 const TemplateTypeParmType *Parm,
3057 const TemplateArgument &ArgPack) {
3058#ifndef NDEBUG
3059 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3060 PEnd = ArgPack.pack_end();
3061 P != PEnd; ++P) {
3062 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3063 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3064 }
3065#endif
3066
3067 llvm::FoldingSetNodeID ID;
3068 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3069 void *InsertPos = 0;
3070 if (SubstTemplateTypeParmPackType *SubstParm
3071 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3072 return QualType(SubstParm, 0);
3073
3074 QualType Canon;
3075 if (!Parm->isCanonicalUnqualified()) {
3076 Canon = getCanonicalType(QualType(Parm, 0));
3077 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3078 ArgPack);
3079 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3080 }
3081
3082 SubstTemplateTypeParmPackType *SubstParm
3083 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3084 ArgPack);
3085 Types.push_back(SubstParm);
3086 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3087 return QualType(SubstParm, 0);
3088}
3089
Douglas Gregoreff93e02009-02-05 23:33:38 +00003090/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003091/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003092/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003093QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003094 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003095 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003096 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003097 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003098 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003099 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003100 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3101
3102 if (TypeParm)
3103 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003104
Chandler Carruth08836322011-05-01 00:51:33 +00003105 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003106 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003107 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003108
3109 TemplateTypeParmType *TypeCheck
3110 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3111 assert(!TypeCheck && "Template type parameter canonical type broken");
3112 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003113 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003114 TypeParm = new (*this, TypeAlignment)
3115 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003116
3117 Types.push_back(TypeParm);
3118 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3119
3120 return QualType(TypeParm, 0);
3121}
3122
John McCalle78aac42010-03-10 03:28:59 +00003123TypeSourceInfo *
3124ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3125 SourceLocation NameLoc,
3126 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003127 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003128 assert(!Name.getAsDependentTemplateName() &&
3129 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003130 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003131
3132 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003133 TemplateSpecializationTypeLoc TL =
3134 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003135 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003136 TL.setTemplateNameLoc(NameLoc);
3137 TL.setLAngleLoc(Args.getLAngleLoc());
3138 TL.setRAngleLoc(Args.getRAngleLoc());
3139 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3140 TL.setArgLocInfo(i, Args[i].getLocInfo());
3141 return DI;
3142}
3143
Mike Stump11289f42009-09-09 15:08:12 +00003144QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003145ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003146 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003147 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003148 assert(!Template.getAsDependentTemplateName() &&
3149 "No dependent template names here!");
3150
John McCall6b51f282009-11-23 01:53:49 +00003151 unsigned NumArgs = Args.size();
3152
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003153 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003154 ArgVec.reserve(NumArgs);
3155 for (unsigned i = 0; i != NumArgs; ++i)
3156 ArgVec.push_back(Args[i].getArgument());
3157
John McCall2408e322010-04-27 00:57:59 +00003158 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003159 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003160}
3161
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003162#ifndef NDEBUG
3163static bool hasAnyPackExpansions(const TemplateArgument *Args,
3164 unsigned NumArgs) {
3165 for (unsigned I = 0; I != NumArgs; ++I)
3166 if (Args[I].isPackExpansion())
3167 return true;
3168
3169 return true;
3170}
3171#endif
3172
John McCall0ad16662009-10-29 08:12:44 +00003173QualType
3174ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003175 const TemplateArgument *Args,
3176 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003177 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003178 assert(!Template.getAsDependentTemplateName() &&
3179 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003180 // Look through qualified template names.
3181 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3182 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003183
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003184 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003185 Template.getAsTemplateDecl() &&
3186 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003187 QualType CanonType;
3188 if (!Underlying.isNull())
3189 CanonType = getCanonicalType(Underlying);
3190 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003191 // We can get here with an alias template when the specialization contains
3192 // a pack expansion that does not match up with a parameter pack.
3193 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3194 "Caller must compute aliased type");
3195 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003196 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3197 NumArgs);
3198 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003199
Douglas Gregora8e02e72009-07-28 23:00:59 +00003200 // Allocate the (non-canonical) template specialization type, but don't
3201 // try to unique it: these types typically have location information that
3202 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003203 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3204 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003205 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003206 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003207 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003208 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3209 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003210
Douglas Gregor8bf42052009-02-09 18:46:07 +00003211 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003212 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003213}
3214
Mike Stump11289f42009-09-09 15:08:12 +00003215QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003216ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3217 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003218 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003219 assert(!Template.getAsDependentTemplateName() &&
3220 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003221
Douglas Gregore29139c2011-03-03 17:04:51 +00003222 // Look through qualified template names.
3223 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3224 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003225
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003226 // Build the canonical template specialization type.
3227 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003228 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003229 CanonArgs.reserve(NumArgs);
3230 for (unsigned I = 0; I != NumArgs; ++I)
3231 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3232
3233 // Determine whether this canonical template specialization type already
3234 // exists.
3235 llvm::FoldingSetNodeID ID;
3236 TemplateSpecializationType::Profile(ID, CanonTemplate,
3237 CanonArgs.data(), NumArgs, *this);
3238
3239 void *InsertPos = 0;
3240 TemplateSpecializationType *Spec
3241 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3242
3243 if (!Spec) {
3244 // Allocate a new canonical template specialization type.
3245 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3246 sizeof(TemplateArgument) * NumArgs),
3247 TypeAlignment);
3248 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3249 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003250 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003251 Types.push_back(Spec);
3252 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3253 }
3254
3255 assert(Spec->isDependentType() &&
3256 "Non-dependent template-id type must have a canonical type");
3257 return QualType(Spec, 0);
3258}
3259
3260QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003261ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3262 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003263 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003264 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003265 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003266
3267 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003268 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003269 if (T)
3270 return QualType(T, 0);
3271
Douglas Gregorc42075a2010-02-04 18:10:26 +00003272 QualType Canon = NamedType;
3273 if (!Canon.isCanonical()) {
3274 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003275 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3276 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003277 (void)CheckT;
3278 }
3279
Abramo Bagnara6150c882010-05-11 21:36:43 +00003280 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003281 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003282 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003283 return QualType(T, 0);
3284}
3285
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003286QualType
Jay Foad39c79802011-01-12 09:06:06 +00003287ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003288 llvm::FoldingSetNodeID ID;
3289 ParenType::Profile(ID, InnerType);
3290
3291 void *InsertPos = 0;
3292 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3293 if (T)
3294 return QualType(T, 0);
3295
3296 QualType Canon = InnerType;
3297 if (!Canon.isCanonical()) {
3298 Canon = getCanonicalType(InnerType);
3299 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3300 assert(!CheckT && "Paren canonical type broken");
3301 (void)CheckT;
3302 }
3303
3304 T = new (*this) ParenType(InnerType, Canon);
3305 Types.push_back(T);
3306 ParenTypes.InsertNode(T, InsertPos);
3307 return QualType(T, 0);
3308}
3309
Douglas Gregor02085352010-03-31 20:19:30 +00003310QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3311 NestedNameSpecifier *NNS,
3312 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003313 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003314 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3315
3316 if (Canon.isNull()) {
3317 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003318 ElaboratedTypeKeyword CanonKeyword = Keyword;
3319 if (Keyword == ETK_None)
3320 CanonKeyword = ETK_Typename;
3321
3322 if (CanonNNS != NNS || CanonKeyword != Keyword)
3323 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003324 }
3325
3326 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003327 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003328
3329 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003330 DependentNameType *T
3331 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003332 if (T)
3333 return QualType(T, 0);
3334
Douglas Gregor02085352010-03-31 20:19:30 +00003335 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003336 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003337 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003338 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003339}
3340
Mike Stump11289f42009-09-09 15:08:12 +00003341QualType
John McCallc392f372010-06-11 00:33:02 +00003342ASTContext::getDependentTemplateSpecializationType(
3343 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003344 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003345 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003346 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003347 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003348 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003349 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3350 ArgCopy.push_back(Args[I].getArgument());
3351 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3352 ArgCopy.size(),
3353 ArgCopy.data());
3354}
3355
3356QualType
3357ASTContext::getDependentTemplateSpecializationType(
3358 ElaboratedTypeKeyword Keyword,
3359 NestedNameSpecifier *NNS,
3360 const IdentifierInfo *Name,
3361 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003362 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003363 assert((!NNS || NNS->isDependent()) &&
3364 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003365
Douglas Gregorc42075a2010-02-04 18:10:26 +00003366 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003367 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3368 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003369
3370 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003371 DependentTemplateSpecializationType *T
3372 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003373 if (T)
3374 return QualType(T, 0);
3375
John McCallc392f372010-06-11 00:33:02 +00003376 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003377
John McCallc392f372010-06-11 00:33:02 +00003378 ElaboratedTypeKeyword CanonKeyword = Keyword;
3379 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3380
3381 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003382 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003383 for (unsigned I = 0; I != NumArgs; ++I) {
3384 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3385 if (!CanonArgs[I].structurallyEquals(Args[I]))
3386 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003387 }
3388
John McCallc392f372010-06-11 00:33:02 +00003389 QualType Canon;
3390 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3391 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3392 Name, NumArgs,
3393 CanonArgs.data());
3394
3395 // Find the insert position again.
3396 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3397 }
3398
3399 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3400 sizeof(TemplateArgument) * NumArgs),
3401 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003402 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003403 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003404 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003405 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003406 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003407}
3408
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003409QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003410 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003411 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003412 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003413
3414 assert(Pattern->containsUnexpandedParameterPack() &&
3415 "Pack expansions must expand one or more parameter packs");
3416 void *InsertPos = 0;
3417 PackExpansionType *T
3418 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3419 if (T)
3420 return QualType(T, 0);
3421
3422 QualType Canon;
3423 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003424 Canon = getCanonicalType(Pattern);
3425 // The canonical type might not contain an unexpanded parameter pack, if it
3426 // contains an alias template specialization which ignores one of its
3427 // parameters.
3428 if (Canon->containsUnexpandedParameterPack()) {
3429 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003430
Richard Smith68eea502012-07-16 00:20:35 +00003431 // Find the insert position again, in case we inserted an element into
3432 // PackExpansionTypes and invalidated our insert position.
3433 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3434 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003435 }
3436
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003437 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003438 Types.push_back(T);
3439 PackExpansionTypes.InsertNode(T, InsertPos);
3440 return QualType(T, 0);
3441}
3442
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003443/// CmpProtocolNames - Comparison predicate for sorting protocols
3444/// alphabetically.
3445static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3446 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003447 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003448}
3449
John McCall8b07ec22010-05-15 11:32:37 +00003450static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003451 unsigned NumProtocols) {
3452 if (NumProtocols == 0) return true;
3453
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003454 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3455 return false;
3456
John McCallfc93cf92009-10-22 22:37:11 +00003457 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003458 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3459 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003460 return false;
3461 return true;
3462}
3463
3464static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003465 unsigned &NumProtocols) {
3466 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003467
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003468 // Sort protocols, keyed by name.
3469 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3470
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003471 // Canonicalize.
3472 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3473 Protocols[I] = Protocols[I]->getCanonicalDecl();
3474
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003475 // Remove duplicates.
3476 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3477 NumProtocols = ProtocolsEnd-Protocols;
3478}
3479
John McCall8b07ec22010-05-15 11:32:37 +00003480QualType ASTContext::getObjCObjectType(QualType BaseType,
3481 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003482 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003483 // If the base type is an interface and there aren't any protocols
3484 // to add, then the interface type will do just fine.
3485 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3486 return BaseType;
3487
3488 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003489 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003490 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003491 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003492 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3493 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003494
John McCall8b07ec22010-05-15 11:32:37 +00003495 // Build the canonical type, which has the canonical base type and
3496 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003497 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003498 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3499 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3500 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003501 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003502 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003503 unsigned UniqueCount = NumProtocols;
3504
John McCallfc93cf92009-10-22 22:37:11 +00003505 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003506 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3507 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003508 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003509 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3510 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003511 }
3512
3513 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003514 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3515 }
3516
3517 unsigned Size = sizeof(ObjCObjectTypeImpl);
3518 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3519 void *Mem = Allocate(Size, TypeAlignment);
3520 ObjCObjectTypeImpl *T =
3521 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3522
3523 Types.push_back(T);
3524 ObjCObjectTypes.InsertNode(T, InsertPos);
3525 return QualType(T, 0);
3526}
3527
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003528/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3529/// protocol list adopt all protocols in QT's qualified-id protocol
3530/// list.
3531bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3532 ObjCInterfaceDecl *IC) {
3533 if (!QT->isObjCQualifiedIdType())
3534 return false;
3535
3536 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3537 // If both the right and left sides have qualifiers.
3538 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3539 E = OPT->qual_end(); I != E; ++I) {
3540 ObjCProtocolDecl *Proto = *I;
3541 if (!IC->ClassImplementsProtocol(Proto, false))
3542 return false;
3543 }
3544 return true;
3545 }
3546 return false;
3547}
3548
3549/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3550/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3551/// of protocols.
3552bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3553 ObjCInterfaceDecl *IDecl) {
3554 if (!QT->isObjCQualifiedIdType())
3555 return false;
3556 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3557 if (!OPT)
3558 return false;
3559 if (!IDecl->hasDefinition())
3560 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003561 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3562 CollectInheritedProtocols(IDecl, InheritedProtocols);
3563 if (InheritedProtocols.empty())
3564 return false;
3565
3566 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3567 InheritedProtocols.begin(),
3568 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003569 // If both the right and left sides have qualifiers.
3570 bool Adopts = false;
3571 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3572 E = OPT->qual_end(); I != E; ++I) {
3573 ObjCProtocolDecl *Proto = *I;
3574 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3575 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3576 break;
3577 }
3578 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003579 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003580 }
3581 return true;
3582}
3583
John McCall8b07ec22010-05-15 11:32:37 +00003584/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3585/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003586QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003587 llvm::FoldingSetNodeID ID;
3588 ObjCObjectPointerType::Profile(ID, ObjectT);
3589
3590 void *InsertPos = 0;
3591 if (ObjCObjectPointerType *QT =
3592 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3593 return QualType(QT, 0);
3594
3595 // Find the canonical object type.
3596 QualType Canonical;
3597 if (!ObjectT.isCanonical()) {
3598 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3599
3600 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003601 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3602 }
3603
Douglas Gregorf85bee62010-02-08 22:59:26 +00003604 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003605 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3606 ObjCObjectPointerType *QType =
3607 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003608
Steve Narofffb4330f2009-06-17 22:40:22 +00003609 Types.push_back(QType);
3610 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003611 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003612}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003613
Douglas Gregor1c283312010-08-11 12:19:30 +00003614/// getObjCInterfaceType - Return the unique reference to the type for the
3615/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003616QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3617 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003618 if (Decl->TypeForDecl)
3619 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003620
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003621 if (PrevDecl) {
3622 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3623 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3624 return QualType(PrevDecl->TypeForDecl, 0);
3625 }
3626
Douglas Gregor7671e532011-12-16 16:34:57 +00003627 // Prefer the definition, if there is one.
3628 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3629 Decl = Def;
3630
Douglas Gregor1c283312010-08-11 12:19:30 +00003631 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3632 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3633 Decl->TypeForDecl = T;
3634 Types.push_back(T);
3635 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003636}
3637
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003638/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3639/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003640/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003641/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003642/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003643QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003644 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003645 if (tofExpr->isTypeDependent()) {
3646 llvm::FoldingSetNodeID ID;
3647 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003648
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003649 void *InsertPos = 0;
3650 DependentTypeOfExprType *Canon
3651 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3652 if (Canon) {
3653 // We already have a "canonical" version of an identical, dependent
3654 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003655 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003656 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003657 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003658 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003659 Canon
3660 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003661 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3662 toe = Canon;
3663 }
3664 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003665 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003666 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003667 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003668 Types.push_back(toe);
3669 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003670}
3671
Steve Naroffa773cd52007-08-01 18:02:17 +00003672/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3673/// TypeOfType AST's. The only motivation to unique these nodes would be
3674/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003675/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003676/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003677QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003678 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003679 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003680 Types.push_back(tot);
3681 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003682}
3683
Anders Carlssonad6bd352009-06-24 21:24:56 +00003684
Anders Carlsson81df7b82009-06-24 19:06:50 +00003685/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3686/// DecltypeType AST's. The only motivation to unique these nodes would be
3687/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003688/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003689/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003690QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003691 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003692
3693 // C++0x [temp.type]p2:
3694 // If an expression e involves a template parameter, decltype(e) denotes a
3695 // unique dependent type. Two such decltype-specifiers refer to the same
3696 // type only if their expressions are equivalent (14.5.6.1).
3697 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003698 llvm::FoldingSetNodeID ID;
3699 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003700
Douglas Gregora21f6c32009-07-30 23:36:40 +00003701 void *InsertPos = 0;
3702 DependentDecltypeType *Canon
3703 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3704 if (Canon) {
3705 // We already have a "canonical" version of an equivalent, dependent
3706 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003707 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003708 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003709 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003710 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003711 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003712 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3713 dt = Canon;
3714 }
3715 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003716 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3717 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003718 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003719 Types.push_back(dt);
3720 return QualType(dt, 0);
3721}
3722
Alexis Hunte852b102011-05-24 22:41:36 +00003723/// getUnaryTransformationType - We don't unique these, since the memory
3724/// savings are minimal and these are rare.
3725QualType ASTContext::getUnaryTransformType(QualType BaseType,
3726 QualType UnderlyingType,
3727 UnaryTransformType::UTTKind Kind)
3728 const {
3729 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003730 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3731 Kind,
3732 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003733 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003734 Types.push_back(Ty);
3735 return QualType(Ty, 0);
3736}
3737
Richard Smith2a7d4812013-05-04 07:00:32 +00003738/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3739/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3740/// canonical deduced-but-dependent 'auto' type.
3741QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003742 bool IsDependent) const {
3743 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003744 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003745
Richard Smith2a7d4812013-05-04 07:00:32 +00003746 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003747 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003748 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003749 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003750 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3751 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003752
Richard Smith74aeef52013-04-26 16:15:35 +00003753 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003754 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003755 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003756 Types.push_back(AT);
3757 if (InsertPos)
3758 AutoTypes.InsertNode(AT, InsertPos);
3759 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003760}
3761
Eli Friedman0dfb8892011-10-06 23:00:33 +00003762/// getAtomicType - Return the uniqued reference to the atomic type for
3763/// the given value type.
3764QualType ASTContext::getAtomicType(QualType T) const {
3765 // Unique pointers, to guarantee there is only one pointer of a particular
3766 // structure.
3767 llvm::FoldingSetNodeID ID;
3768 AtomicType::Profile(ID, T);
3769
3770 void *InsertPos = 0;
3771 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3772 return QualType(AT, 0);
3773
3774 // If the atomic value type isn't canonical, this won't be a canonical type
3775 // either, so fill in the canonical type field.
3776 QualType Canonical;
3777 if (!T.isCanonical()) {
3778 Canonical = getAtomicType(getCanonicalType(T));
3779
3780 // Get the new insert position for the node we care about.
3781 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3782 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3783 }
3784 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3785 Types.push_back(New);
3786 AtomicTypes.InsertNode(New, InsertPos);
3787 return QualType(New, 0);
3788}
3789
Richard Smith02e85f32011-04-14 22:09:26 +00003790/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3791QualType ASTContext::getAutoDeductType() const {
3792 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003793 AutoDeductTy = QualType(
3794 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003795 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003796 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003797 return AutoDeductTy;
3798}
3799
3800/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3801QualType ASTContext::getAutoRRefDeductType() const {
3802 if (AutoRRefDeductTy.isNull())
3803 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3804 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3805 return AutoRRefDeductTy;
3806}
3807
Chris Lattnerfb072462007-01-23 05:45:31 +00003808/// getTagDeclType - Return the unique reference to the type for the
3809/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003810QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003811 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003812 // FIXME: What is the design on getTagDeclType when it requires casting
3813 // away const? mutable?
3814 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003815}
3816
Mike Stump11289f42009-09-09 15:08:12 +00003817/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3818/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3819/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003820CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003821 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003822}
Chris Lattnerfb072462007-01-23 05:45:31 +00003823
Hans Wennborg27541db2011-10-27 08:29:09 +00003824/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3825CanQualType ASTContext::getIntMaxType() const {
3826 return getFromTargetType(Target->getIntMaxType());
3827}
3828
3829/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3830CanQualType ASTContext::getUIntMaxType() const {
3831 return getFromTargetType(Target->getUIntMaxType());
3832}
3833
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003834/// getSignedWCharType - Return the type of "signed wchar_t".
3835/// Used when in C++, as a GCC extension.
3836QualType ASTContext::getSignedWCharType() const {
3837 // FIXME: derive from "Target" ?
3838 return WCharTy;
3839}
3840
3841/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3842/// Used when in C++, as a GCC extension.
3843QualType ASTContext::getUnsignedWCharType() const {
3844 // FIXME: derive from "Target" ?
3845 return UnsignedIntTy;
3846}
3847
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003848QualType ASTContext::getIntPtrType() const {
3849 return getFromTargetType(Target->getIntPtrType());
3850}
3851
3852QualType ASTContext::getUIntPtrType() const {
3853 return getCorrespondingUnsignedType(getIntPtrType());
3854}
3855
Hans Wennborg27541db2011-10-27 08:29:09 +00003856/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003857/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3858QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003859 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003860}
3861
Eli Friedman4e91899e2012-11-27 02:58:24 +00003862/// \brief Return the unique type for "pid_t" defined in
3863/// <sys/types.h>. We need this to compute the correct type for vfork().
3864QualType ASTContext::getProcessIDType() const {
3865 return getFromTargetType(Target->getProcessIDType());
3866}
3867
Chris Lattnera21ad802008-04-02 05:18:44 +00003868//===----------------------------------------------------------------------===//
3869// Type Operators
3870//===----------------------------------------------------------------------===//
3871
Jay Foad39c79802011-01-12 09:06:06 +00003872CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003873 // Push qualifiers into arrays, and then discard any remaining
3874 // qualifiers.
3875 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003876 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003877 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003878 QualType Result;
3879 if (isa<ArrayType>(Ty)) {
3880 Result = getArrayDecayedType(QualType(Ty,0));
3881 } else if (isa<FunctionType>(Ty)) {
3882 Result = getPointerType(QualType(Ty, 0));
3883 } else {
3884 Result = QualType(Ty, 0);
3885 }
3886
3887 return CanQualType::CreateUnsafe(Result);
3888}
3889
John McCall6c9dd522011-01-18 07:41:22 +00003890QualType ASTContext::getUnqualifiedArrayType(QualType type,
3891 Qualifiers &quals) {
3892 SplitQualType splitType = type.getSplitUnqualifiedType();
3893
3894 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3895 // the unqualified desugared type and then drops it on the floor.
3896 // We then have to strip that sugar back off with
3897 // getUnqualifiedDesugaredType(), which is silly.
3898 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003899 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003900
3901 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003902 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003903 quals = splitType.Quals;
3904 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003905 }
3906
John McCall6c9dd522011-01-18 07:41:22 +00003907 // Otherwise, recurse on the array's element type.
3908 QualType elementType = AT->getElementType();
3909 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3910
3911 // If that didn't change the element type, AT has no qualifiers, so we
3912 // can just use the results in splitType.
3913 if (elementType == unqualElementType) {
3914 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003915 quals = splitType.Quals;
3916 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003917 }
3918
3919 // Otherwise, add in the qualifiers from the outermost type, then
3920 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003921 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003922
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003923 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003924 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003925 CAT->getSizeModifier(), 0);
3926 }
3927
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003928 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003929 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003930 }
3931
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003932 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003933 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003934 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003935 VAT->getSizeModifier(),
3936 VAT->getIndexTypeCVRQualifiers(),
3937 VAT->getBracketsRange());
3938 }
3939
3940 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003941 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003942 DSAT->getSizeModifier(), 0,
3943 SourceRange());
3944}
3945
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003946/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3947/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3948/// they point to and return true. If T1 and T2 aren't pointer types
3949/// or pointer-to-member types, or if they are not similar at this
3950/// level, returns false and leaves T1 and T2 unchanged. Top-level
3951/// qualifiers on T1 and T2 are ignored. This function will typically
3952/// be called in a loop that successively "unwraps" pointer and
3953/// pointer-to-member types to compare them at each level.
3954bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3955 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3956 *T2PtrType = T2->getAs<PointerType>();
3957 if (T1PtrType && T2PtrType) {
3958 T1 = T1PtrType->getPointeeType();
3959 T2 = T2PtrType->getPointeeType();
3960 return true;
3961 }
3962
3963 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3964 *T2MPType = T2->getAs<MemberPointerType>();
3965 if (T1MPType && T2MPType &&
3966 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3967 QualType(T2MPType->getClass(), 0))) {
3968 T1 = T1MPType->getPointeeType();
3969 T2 = T2MPType->getPointeeType();
3970 return true;
3971 }
3972
David Blaikiebbafb8a2012-03-11 07:00:24 +00003973 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003974 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3975 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3976 if (T1OPType && T2OPType) {
3977 T1 = T1OPType->getPointeeType();
3978 T2 = T2OPType->getPointeeType();
3979 return true;
3980 }
3981 }
3982
3983 // FIXME: Block pointers, too?
3984
3985 return false;
3986}
3987
Jay Foad39c79802011-01-12 09:06:06 +00003988DeclarationNameInfo
3989ASTContext::getNameForTemplate(TemplateName Name,
3990 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003991 switch (Name.getKind()) {
3992 case TemplateName::QualifiedTemplate:
3993 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003994 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003995 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3996 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003997
John McCalld9dfe3a2011-06-30 08:33:18 +00003998 case TemplateName::OverloadedTemplate: {
3999 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4000 // DNInfo work in progress: CHECKME: what about DNLoc?
4001 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4002 }
4003
4004 case TemplateName::DependentTemplate: {
4005 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004006 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004007 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004008 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4009 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004010 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004011 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4012 // DNInfo work in progress: FIXME: source locations?
4013 DeclarationNameLoc DNLoc;
4014 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4015 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4016 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004017 }
4018 }
4019
John McCalld9dfe3a2011-06-30 08:33:18 +00004020 case TemplateName::SubstTemplateTemplateParm: {
4021 SubstTemplateTemplateParmStorage *subst
4022 = Name.getAsSubstTemplateTemplateParm();
4023 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4024 NameLoc);
4025 }
4026
4027 case TemplateName::SubstTemplateTemplateParmPack: {
4028 SubstTemplateTemplateParmPackStorage *subst
4029 = Name.getAsSubstTemplateTemplateParmPack();
4030 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4031 NameLoc);
4032 }
4033 }
4034
4035 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004036}
4037
Jay Foad39c79802011-01-12 09:06:06 +00004038TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004039 switch (Name.getKind()) {
4040 case TemplateName::QualifiedTemplate:
4041 case TemplateName::Template: {
4042 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004043 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004044 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004045 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4046
4047 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004048 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004049 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004050
John McCalld9dfe3a2011-06-30 08:33:18 +00004051 case TemplateName::OverloadedTemplate:
4052 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004053
John McCalld9dfe3a2011-06-30 08:33:18 +00004054 case TemplateName::DependentTemplate: {
4055 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4056 assert(DTN && "Non-dependent template names must refer to template decls.");
4057 return DTN->CanonicalTemplateName;
4058 }
4059
4060 case TemplateName::SubstTemplateTemplateParm: {
4061 SubstTemplateTemplateParmStorage *subst
4062 = Name.getAsSubstTemplateTemplateParm();
4063 return getCanonicalTemplateName(subst->getReplacement());
4064 }
4065
4066 case TemplateName::SubstTemplateTemplateParmPack: {
4067 SubstTemplateTemplateParmPackStorage *subst
4068 = Name.getAsSubstTemplateTemplateParmPack();
4069 TemplateTemplateParmDecl *canonParameter
4070 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4071 TemplateArgument canonArgPack
4072 = getCanonicalTemplateArgument(subst->getArgumentPack());
4073 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4074 }
4075 }
4076
4077 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004078}
4079
Douglas Gregoradee3e32009-11-11 23:06:43 +00004080bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4081 X = getCanonicalTemplateName(X);
4082 Y = getCanonicalTemplateName(Y);
4083 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4084}
4085
Mike Stump11289f42009-09-09 15:08:12 +00004086TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004087ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004088 switch (Arg.getKind()) {
4089 case TemplateArgument::Null:
4090 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004091
Douglas Gregora8e02e72009-07-28 23:00:59 +00004092 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004093 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004094
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004095 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004096 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4097 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004098 }
Mike Stump11289f42009-09-09 15:08:12 +00004099
Eli Friedmanb826a002012-09-26 02:36:12 +00004100 case TemplateArgument::NullPtr:
4101 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4102 /*isNullPtr*/true);
4103
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004104 case TemplateArgument::Template:
4105 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004106
4107 case TemplateArgument::TemplateExpansion:
4108 return TemplateArgument(getCanonicalTemplateName(
4109 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004110 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004111
Douglas Gregora8e02e72009-07-28 23:00:59 +00004112 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004113 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004114
Douglas Gregora8e02e72009-07-28 23:00:59 +00004115 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004116 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004117
Douglas Gregora8e02e72009-07-28 23:00:59 +00004118 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004119 if (Arg.pack_size() == 0)
4120 return Arg;
4121
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004122 TemplateArgument *CanonArgs
4123 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004124 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004125 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004126 AEnd = Arg.pack_end();
4127 A != AEnd; (void)++A, ++Idx)
4128 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004129
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004130 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004131 }
4132 }
4133
4134 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004135 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004136}
4137
Douglas Gregor333489b2009-03-27 23:10:48 +00004138NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004139ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004140 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004141 return 0;
4142
4143 switch (NNS->getKind()) {
4144 case NestedNameSpecifier::Identifier:
4145 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004146 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004147 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4148 NNS->getAsIdentifier());
4149
4150 case NestedNameSpecifier::Namespace:
4151 // A namespace is canonical; build a nested-name-specifier with
4152 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004153 return NestedNameSpecifier::Create(*this, 0,
4154 NNS->getAsNamespace()->getOriginalNamespace());
4155
4156 case NestedNameSpecifier::NamespaceAlias:
4157 // A namespace is canonical; build a nested-name-specifier with
4158 // this namespace and no prefix.
4159 return NestedNameSpecifier::Create(*this, 0,
4160 NNS->getAsNamespaceAlias()->getNamespace()
4161 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004162
4163 case NestedNameSpecifier::TypeSpec:
4164 case NestedNameSpecifier::TypeSpecWithTemplate: {
4165 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004166
4167 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4168 // break it apart into its prefix and identifier, then reconsititute those
4169 // as the canonical nested-name-specifier. This is required to canonicalize
4170 // a dependent nested-name-specifier involving typedefs of dependent-name
4171 // types, e.g.,
4172 // typedef typename T::type T1;
4173 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004174 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4175 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004176 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004177
Eli Friedman5358a0a2012-03-03 04:09:56 +00004178 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4179 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4180 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004181 return NestedNameSpecifier::Create(*this, 0, false,
4182 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004183 }
4184
4185 case NestedNameSpecifier::Global:
4186 // The global specifier is canonical and unique.
4187 return NNS;
4188 }
4189
David Blaikie8a40f702012-01-17 06:56:22 +00004190 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004191}
4192
Chris Lattner7adf0762008-08-04 07:31:14 +00004193
Jay Foad39c79802011-01-12 09:06:06 +00004194const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004195 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004196 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004197 // Handle the common positive case fast.
4198 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4199 return AT;
4200 }
Mike Stump11289f42009-09-09 15:08:12 +00004201
John McCall8ccfcb52009-09-24 19:53:00 +00004202 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004203 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004204 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004205
John McCall8ccfcb52009-09-24 19:53:00 +00004206 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004207 // implements C99 6.7.3p8: "If the specification of an array type includes
4208 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004209
Chris Lattner7adf0762008-08-04 07:31:14 +00004210 // If we get here, we either have type qualifiers on the type, or we have
4211 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004212 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004213
John McCall33ddac02011-01-19 10:06:00 +00004214 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004215 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004216
Chris Lattner7adf0762008-08-04 07:31:14 +00004217 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004218 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004219 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004220 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004221
Chris Lattner7adf0762008-08-04 07:31:14 +00004222 // Otherwise, we have an array and we have qualifiers on it. Push the
4223 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004224 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004225
Chris Lattner7adf0762008-08-04 07:31:14 +00004226 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4227 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4228 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004229 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004230 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4231 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4232 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004233 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004234
Mike Stump11289f42009-09-09 15:08:12 +00004235 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004236 = dyn_cast<DependentSizedArrayType>(ATy))
4237 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004238 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004239 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004240 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004241 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004242 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004243
Chris Lattner7adf0762008-08-04 07:31:14 +00004244 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004245 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004246 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004247 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004248 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004249 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004250}
4251
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004252QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004253 if (T->isArrayType() || T->isFunctionType())
4254 return getDecayedType(T);
4255 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004256}
4257
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004258QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004259 T = getVariableArrayDecayedType(T);
4260 T = getAdjustedParameterType(T);
4261 return T.getUnqualifiedType();
4262}
4263
Chris Lattnera21ad802008-04-02 05:18:44 +00004264/// getArrayDecayedType - Return the properly qualified result of decaying the
4265/// specified array type to a pointer. This operation is non-trivial when
4266/// handling typedefs etc. The canonical type of "T" must be an array type,
4267/// this returns a pointer to a properly qualified element of the array.
4268///
4269/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004270QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004271 // Get the element type with 'getAsArrayType' so that we don't lose any
4272 // typedefs in the element type of the array. This also handles propagation
4273 // of type qualifiers from the array type into the element type if present
4274 // (C99 6.7.3p8).
4275 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4276 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004277
Chris Lattner7adf0762008-08-04 07:31:14 +00004278 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004279
4280 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004281 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004282}
4283
John McCall33ddac02011-01-19 10:06:00 +00004284QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4285 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004286}
4287
John McCall33ddac02011-01-19 10:06:00 +00004288QualType ASTContext::getBaseElementType(QualType type) const {
4289 Qualifiers qs;
4290 while (true) {
4291 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004292 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004293 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004294
John McCall33ddac02011-01-19 10:06:00 +00004295 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004296 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004297 }
Mike Stump11289f42009-09-09 15:08:12 +00004298
John McCall33ddac02011-01-19 10:06:00 +00004299 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004300}
4301
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004302/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004303uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004304ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4305 uint64_t ElementCount = 1;
4306 do {
4307 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004308 CA = dyn_cast_or_null<ConstantArrayType>(
4309 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004310 } while (CA);
4311 return ElementCount;
4312}
4313
Steve Naroff0af91202007-04-27 21:51:21 +00004314/// getFloatingRank - Return a relative rank for floating point types.
4315/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004316static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004317 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004318 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004319
John McCall9dd450b2009-09-21 23:43:11 +00004320 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4321 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004322 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004323 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004324 case BuiltinType::Float: return FloatRank;
4325 case BuiltinType::Double: return DoubleRank;
4326 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004327 }
4328}
4329
Mike Stump11289f42009-09-09 15:08:12 +00004330/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4331/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004332/// 'typeDomain' is a real floating point or complex type.
4333/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004334QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4335 QualType Domain) const {
4336 FloatingRank EltRank = getFloatingRank(Size);
4337 if (Domain->isComplexType()) {
4338 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004339 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004340 case FloatRank: return FloatComplexTy;
4341 case DoubleRank: return DoubleComplexTy;
4342 case LongDoubleRank: return LongDoubleComplexTy;
4343 }
Steve Naroff0af91202007-04-27 21:51:21 +00004344 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004345
4346 assert(Domain->isRealFloatingType() && "Unknown domain!");
4347 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004348 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004349 case FloatRank: return FloatTy;
4350 case DoubleRank: return DoubleTy;
4351 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004352 }
David Blaikief47fa302012-01-17 02:30:50 +00004353 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004354}
4355
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004356/// getFloatingTypeOrder - Compare the rank of the two specified floating
4357/// point types, ignoring the domain of the type (i.e. 'double' ==
4358/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004359/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004360int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004361 FloatingRank LHSR = getFloatingRank(LHS);
4362 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004363
Chris Lattnerb90739d2008-04-06 23:38:49 +00004364 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004365 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004366 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004367 return 1;
4368 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004369}
4370
Chris Lattner76a00cf2008-04-06 22:59:24 +00004371/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4372/// routine will assert if passed a built-in type that isn't an integer or enum,
4373/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004374unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004375 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004376
Chris Lattner76a00cf2008-04-06 22:59:24 +00004377 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004378 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004379 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004380 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004381 case BuiltinType::Char_S:
4382 case BuiltinType::Char_U:
4383 case BuiltinType::SChar:
4384 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004385 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004386 case BuiltinType::Short:
4387 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004388 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004389 case BuiltinType::Int:
4390 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004391 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004392 case BuiltinType::Long:
4393 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004394 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004395 case BuiltinType::LongLong:
4396 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004397 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004398 case BuiltinType::Int128:
4399 case BuiltinType::UInt128:
4400 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004401 }
4402}
4403
Eli Friedman629ffb92009-08-20 04:21:42 +00004404/// \brief Whether this is a promotable bitfield reference according
4405/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4406///
4407/// \returns the type this bit-field will promote to, or NULL if no
4408/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004409QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004410 if (E->isTypeDependent() || E->isValueDependent())
4411 return QualType();
4412
John McCalld25db7e2013-05-06 21:39:12 +00004413 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004414 if (!Field)
4415 return QualType();
4416
4417 QualType FT = Field->getType();
4418
Richard Smithcaf33902011-10-10 18:28:20 +00004419 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004420 uint64_t IntSize = getTypeSize(IntTy);
4421 // GCC extension compatibility: if the bit-field size is less than or equal
4422 // to the size of int, it gets promoted no matter what its type is.
4423 // For instance, unsigned long bf : 4 gets promoted to signed int.
4424 if (BitWidth < IntSize)
4425 return IntTy;
4426
4427 if (BitWidth == IntSize)
4428 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4429
4430 // Types bigger than int are not subject to promotions, and therefore act
4431 // like the base type.
4432 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4433 // is ridiculous.
4434 return QualType();
4435}
4436
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004437/// getPromotedIntegerType - Returns the type that Promotable will
4438/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4439/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004440QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004441 assert(!Promotable.isNull());
4442 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004443 if (const EnumType *ET = Promotable->getAs<EnumType>())
4444 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004445
4446 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4447 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4448 // (3.9.1) can be converted to a prvalue of the first of the following
4449 // types that can represent all the values of its underlying type:
4450 // int, unsigned int, long int, unsigned long int, long long int, or
4451 // unsigned long long int [...]
4452 // FIXME: Is there some better way to compute this?
4453 if (BT->getKind() == BuiltinType::WChar_S ||
4454 BT->getKind() == BuiltinType::WChar_U ||
4455 BT->getKind() == BuiltinType::Char16 ||
4456 BT->getKind() == BuiltinType::Char32) {
4457 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4458 uint64_t FromSize = getTypeSize(BT);
4459 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4460 LongLongTy, UnsignedLongLongTy };
4461 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4462 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4463 if (FromSize < ToSize ||
4464 (FromSize == ToSize &&
4465 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4466 return PromoteTypes[Idx];
4467 }
4468 llvm_unreachable("char type should fit into long long");
4469 }
4470 }
4471
4472 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004473 if (Promotable->isSignedIntegerType())
4474 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004475 uint64_t PromotableSize = getIntWidth(Promotable);
4476 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004477 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4478 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4479}
4480
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004481/// \brief Recurses in pointer/array types until it finds an objc retainable
4482/// type and returns its ownership.
4483Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4484 while (!T.isNull()) {
4485 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4486 return T.getObjCLifetime();
4487 if (T->isArrayType())
4488 T = getBaseElementType(T);
4489 else if (const PointerType *PT = T->getAs<PointerType>())
4490 T = PT->getPointeeType();
4491 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004492 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004493 else
4494 break;
4495 }
4496
4497 return Qualifiers::OCL_None;
4498}
4499
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004500static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4501 // Incomplete enum types are not treated as integer types.
4502 // FIXME: In C++, enum types are never integer types.
4503 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4504 return ET->getDecl()->getIntegerType().getTypePtr();
4505 return NULL;
4506}
4507
Mike Stump11289f42009-09-09 15:08:12 +00004508/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004509/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004510/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004511int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004512 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4513 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004514
4515 // Unwrap enums to their underlying type.
4516 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4517 LHSC = getIntegerTypeForEnum(ET);
4518 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4519 RHSC = getIntegerTypeForEnum(ET);
4520
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004521 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004522
Chris Lattner76a00cf2008-04-06 22:59:24 +00004523 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4524 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004525
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004526 unsigned LHSRank = getIntegerRank(LHSC);
4527 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004528
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004529 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4530 if (LHSRank == RHSRank) return 0;
4531 return LHSRank > RHSRank ? 1 : -1;
4532 }
Mike Stump11289f42009-09-09 15:08:12 +00004533
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004534 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4535 if (LHSUnsigned) {
4536 // If the unsigned [LHS] type is larger, return it.
4537 if (LHSRank >= RHSRank)
4538 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004539
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004540 // If the signed type can represent all values of the unsigned type, it
4541 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004542 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004543 return -1;
4544 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004545
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004546 // If the unsigned [RHS] type is larger, return it.
4547 if (RHSRank >= LHSRank)
4548 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004549
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004550 // If the signed type can represent all values of the unsigned type, it
4551 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004552 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004553 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004554}
Anders Carlsson98f07902007-08-17 05:31:46 +00004555
Mike Stump11289f42009-09-09 15:08:12 +00004556// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004557QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004558 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004559 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004560 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004561
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004562 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004563
Anders Carlsson98f07902007-08-17 05:31:46 +00004564 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004565 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004566 // int flags;
4567 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004568 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004569 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004570 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004571 FieldTypes[3] = LongTy;
4572
Anders Carlsson98f07902007-08-17 05:31:46 +00004573 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004574 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004575 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004576 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004577 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004578 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004579 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004580 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004581 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004582 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004583 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004584 }
4585
Douglas Gregord5058122010-02-11 01:19:42 +00004586 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004587 }
Mike Stump11289f42009-09-09 15:08:12 +00004588
Anders Carlsson98f07902007-08-17 05:31:46 +00004589 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004590}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004591
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004592QualType ASTContext::getObjCSuperType() const {
4593 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004594 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004595 TUDecl->addDecl(ObjCSuperTypeDecl);
4596 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4597 }
4598 return ObjCSuperType;
4599}
4600
Douglas Gregor512b0772009-04-23 22:29:11 +00004601void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004602 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004603 assert(Rec && "Invalid CFConstantStringType");
4604 CFConstantStringTypeDecl = Rec->getDecl();
4605}
4606
Jay Foad39c79802011-01-12 09:06:06 +00004607QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004608 if (BlockDescriptorType)
4609 return getTagDeclType(BlockDescriptorType);
4610
Alp Toker2dea15b2013-12-17 01:22:38 +00004611 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004612 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004613 RD = buildImplicitRecord("__block_descriptor");
4614 RD->startDefinition();
4615
Mike Stumpd0153282009-10-20 02:12:22 +00004616 QualType FieldTypes[] = {
4617 UnsignedLongTy,
4618 UnsignedLongTy,
4619 };
4620
Craig Topperd6d31ac2013-07-15 08:24:27 +00004621 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004622 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004623 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004624 };
4625
4626 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004627 FieldDecl *Field = FieldDecl::Create(
4628 *this, RD, SourceLocation(), SourceLocation(),
4629 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4630 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004631 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004632 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004633 }
4634
Alp Toker2dea15b2013-12-17 01:22:38 +00004635 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004636
Alp Toker2dea15b2013-12-17 01:22:38 +00004637 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004638
4639 return getTagDeclType(BlockDescriptorType);
4640}
4641
Jay Foad39c79802011-01-12 09:06:06 +00004642QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004643 if (BlockDescriptorExtendedType)
4644 return getTagDeclType(BlockDescriptorExtendedType);
4645
Alp Toker2dea15b2013-12-17 01:22:38 +00004646 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004647 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004648 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4649 RD->startDefinition();
4650
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004651 QualType FieldTypes[] = {
4652 UnsignedLongTy,
4653 UnsignedLongTy,
4654 getPointerType(VoidPtrTy),
4655 getPointerType(VoidPtrTy)
4656 };
4657
Craig Topperd6d31ac2013-07-15 08:24:27 +00004658 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004659 "reserved",
4660 "Size",
4661 "CopyFuncPtr",
4662 "DestroyFuncPtr"
4663 };
4664
4665 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004666 FieldDecl *Field = FieldDecl::Create(
4667 *this, RD, SourceLocation(), SourceLocation(),
4668 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4669 /*BitWidth=*/0,
4670 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004671 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004672 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004673 }
4674
Alp Toker2dea15b2013-12-17 01:22:38 +00004675 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004676
Alp Toker2dea15b2013-12-17 01:22:38 +00004677 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004678 return getTagDeclType(BlockDescriptorExtendedType);
4679}
4680
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004681/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4682/// requires copy/dispose. Note that this must match the logic
4683/// in buildByrefHelpers.
4684bool ASTContext::BlockRequiresCopying(QualType Ty,
4685 const VarDecl *D) {
4686 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4687 const Expr *copyExpr = getBlockVarCopyInits(D);
4688 if (!copyExpr && record->hasTrivialDestructor()) return false;
4689
Mike Stump94967902009-10-21 18:16:27 +00004690 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004691 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004692
4693 if (!Ty->isObjCRetainableType()) return false;
4694
4695 Qualifiers qs = Ty.getQualifiers();
4696
4697 // If we have lifetime, that dominates.
4698 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4699 assert(getLangOpts().ObjCAutoRefCount);
4700
4701 switch (lifetime) {
4702 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4703
4704 // These are just bits as far as the runtime is concerned.
4705 case Qualifiers::OCL_ExplicitNone:
4706 case Qualifiers::OCL_Autoreleasing:
4707 return false;
4708
4709 // Tell the runtime that this is ARC __weak, called by the
4710 // byref routines.
4711 case Qualifiers::OCL_Weak:
4712 // ARC __strong __block variables need to be retained.
4713 case Qualifiers::OCL_Strong:
4714 return true;
4715 }
4716 llvm_unreachable("fell out of lifetime switch!");
4717 }
4718 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4719 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004720}
4721
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004722bool ASTContext::getByrefLifetime(QualType Ty,
4723 Qualifiers::ObjCLifetime &LifeTime,
4724 bool &HasByrefExtendedLayout) const {
4725
4726 if (!getLangOpts().ObjC1 ||
4727 getLangOpts().getGC() != LangOptions::NonGC)
4728 return false;
4729
4730 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004731 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004732 HasByrefExtendedLayout = true;
4733 LifeTime = Qualifiers::OCL_None;
4734 }
4735 else if (getLangOpts().ObjCAutoRefCount)
4736 LifeTime = Ty.getObjCLifetime();
4737 // MRR.
4738 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4739 LifeTime = Qualifiers::OCL_ExplicitNone;
4740 else
4741 LifeTime = Qualifiers::OCL_None;
4742 return true;
4743}
4744
Douglas Gregorbab8a962011-09-08 01:46:34 +00004745TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4746 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004747 ObjCInstanceTypeDecl =
4748 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004749 return ObjCInstanceTypeDecl;
4750}
4751
Anders Carlsson18acd442007-10-29 06:33:42 +00004752// This returns true if a type has been typedefed to BOOL:
4753// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004754static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004755 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004756 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4757 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004758
Anders Carlssond8499822007-10-29 05:01:08 +00004759 return false;
4760}
4761
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004762/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004763/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004764CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004765 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4766 return CharUnits::Zero();
4767
Ken Dyck40775002010-01-11 17:06:35 +00004768 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004769
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004770 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004771 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004772 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004773 // Treat arrays as pointers, since that's how they're passed in.
4774 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004775 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004776 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004777}
4778
4779static inline
4780std::string charUnitsToString(const CharUnits &CU) {
4781 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004782}
4783
John McCall351762c2011-02-07 10:33:21 +00004784/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004785/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004786std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4787 std::string S;
4788
David Chisnall950a9512009-11-17 19:33:30 +00004789 const BlockDecl *Decl = Expr->getBlockDecl();
4790 QualType BlockTy =
4791 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4792 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004793 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004794 getObjCEncodingForMethodParameter(
4795 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4796 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004797 else
Alp Toker314cc812014-01-25 16:55:45 +00004798 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004799 // Compute size of all parameters.
4800 // Start with computing size of a pointer in number of bytes.
4801 // FIXME: There might(should) be a better way of doing this computation!
4802 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004803 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4804 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004805 for (auto PI : Decl->params()) {
4806 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004807 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004808 if (sz.isZero())
4809 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004810 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004811 ParmOffset += sz;
4812 }
4813 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004814 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004815 // Block pointer and offset.
4816 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004817
4818 // Argument types.
4819 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004820 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004821 QualType PType = PVDecl->getOriginalType();
4822 if (const ArrayType *AT =
4823 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4824 // Use array's original type only if it has known number of
4825 // elements.
4826 if (!isa<ConstantArrayType>(AT))
4827 PType = PVDecl->getType();
4828 } else if (PType->isFunctionType())
4829 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004830 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004831 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4832 S, true /*Extended*/);
4833 else
4834 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004835 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004836 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004837 }
John McCall351762c2011-02-07 10:33:21 +00004838
4839 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004840}
4841
Douglas Gregora9d84932011-05-27 01:19:52 +00004842bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004843 std::string& S) {
4844 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004845 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004846 CharUnits ParmOffset;
4847 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004848 for (auto PI : Decl->params()) {
4849 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004850 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004851 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004852 continue;
4853
David Chisnall50e4eba2010-12-30 14:05:53 +00004854 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004855 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004856 ParmOffset += sz;
4857 }
4858 S += charUnitsToString(ParmOffset);
4859 ParmOffset = CharUnits::Zero();
4860
4861 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004862 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004863 QualType PType = PVDecl->getOriginalType();
4864 if (const ArrayType *AT =
4865 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4866 // Use array's original type only if it has known number of
4867 // elements.
4868 if (!isa<ConstantArrayType>(AT))
4869 PType = PVDecl->getType();
4870 } else if (PType->isFunctionType())
4871 PType = PVDecl->getType();
4872 getObjCEncodingForType(PType, S);
4873 S += charUnitsToString(ParmOffset);
4874 ParmOffset += getObjCEncodingTypeSize(PType);
4875 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004876
4877 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004878}
4879
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004880/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4881/// method parameter or return type. If Extended, include class names and
4882/// block object types.
4883void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4884 QualType T, std::string& S,
4885 bool Extended) const {
4886 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4887 getObjCEncodingForTypeQualifier(QT, S);
4888 // Encode parameter type.
4889 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4890 true /*OutermostType*/,
4891 false /*EncodingProperty*/,
4892 false /*StructField*/,
4893 Extended /*EncodeBlockParameters*/,
4894 Extended /*EncodeClassNames*/);
4895}
4896
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004897/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004898/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004899bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004900 std::string& S,
4901 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004902 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004903 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004904 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4905 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004906 // Compute size of all parameters.
4907 // Start with computing size of a pointer in number of bytes.
4908 // FIXME: There might(should) be a better way of doing this computation!
4909 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004910 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004911 // The first two arguments (self and _cmd) are pointers; account for
4912 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004913 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004914 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004915 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004916 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004917 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004918 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004919 continue;
4920
Ken Dyck40775002010-01-11 17:06:35 +00004921 assert (sz.isPositive() &&
4922 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004923 ParmOffset += sz;
4924 }
Ken Dyck40775002010-01-11 17:06:35 +00004925 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004926 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004927 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004928
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004929 // Argument types.
4930 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004931 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004932 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004933 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004934 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004935 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004936 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4937 // Use array's original type only if it has known number of
4938 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004939 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004940 PType = PVDecl->getType();
4941 } else if (PType->isFunctionType())
4942 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004943 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4944 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004945 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004946 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004947 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004948
4949 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004950}
4951
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004952ObjCPropertyImplDecl *
4953ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4954 const ObjCPropertyDecl *PD,
4955 const Decl *Container) const {
4956 if (!Container)
4957 return 0;
4958 if (const ObjCCategoryImplDecl *CID =
4959 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4960 for (ObjCCategoryImplDecl::propimpl_iterator
4961 i = CID->propimpl_begin(), e = CID->propimpl_end();
4962 i != e; ++i) {
4963 ObjCPropertyImplDecl *PID = *i;
4964 if (PID->getPropertyDecl() == PD)
4965 return PID;
4966 }
4967 } else {
4968 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4969 for (ObjCCategoryImplDecl::propimpl_iterator
4970 i = OID->propimpl_begin(), e = OID->propimpl_end();
4971 i != e; ++i) {
4972 ObjCPropertyImplDecl *PID = *i;
4973 if (PID->getPropertyDecl() == PD)
4974 return PID;
4975 }
4976 }
4977 return 0;
4978}
4979
Daniel Dunbar4932b362008-08-28 04:38:10 +00004980/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004981/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004982/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4983/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004984/// Property attributes are stored as a comma-delimited C string. The simple
4985/// attributes readonly and bycopy are encoded as single characters. The
4986/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4987/// encoded as single characters, followed by an identifier. Property types
4988/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004989/// these attributes are defined by the following enumeration:
4990/// @code
4991/// enum PropertyAttributes {
4992/// kPropertyReadOnly = 'R', // property is read-only.
4993/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4994/// kPropertyByref = '&', // property is a reference to the value last assigned
4995/// kPropertyDynamic = 'D', // property is dynamic
4996/// kPropertyGetter = 'G', // followed by getter selector name
4997/// kPropertySetter = 'S', // followed by setter selector name
4998/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004999/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005000/// kPropertyWeak = 'W' // 'weak' property
5001/// kPropertyStrong = 'P' // property GC'able
5002/// kPropertyNonAtomic = 'N' // property non-atomic
5003/// };
5004/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005005void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005006 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005007 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005008 // Collect information from the property implementation decl(s).
5009 bool Dynamic = false;
5010 ObjCPropertyImplDecl *SynthesizePID = 0;
5011
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005012 if (ObjCPropertyImplDecl *PropertyImpDecl =
5013 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5014 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5015 Dynamic = true;
5016 else
5017 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005018 }
5019
5020 // FIXME: This is not very efficient.
5021 S = "T";
5022
5023 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005024 // GCC has some special rules regarding encoding of properties which
5025 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005026 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005027 true /* outermost type */,
5028 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005029
5030 if (PD->isReadOnly()) {
5031 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005032 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5033 S += ",C";
5034 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5035 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005036 } else {
5037 switch (PD->getSetterKind()) {
5038 case ObjCPropertyDecl::Assign: break;
5039 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005040 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005041 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005042 }
5043 }
5044
5045 // It really isn't clear at all what this means, since properties
5046 // are "dynamic by default".
5047 if (Dynamic)
5048 S += ",D";
5049
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005050 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5051 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005052
Daniel Dunbar4932b362008-08-28 04:38:10 +00005053 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5054 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005055 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005056 }
5057
5058 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5059 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005060 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005061 }
5062
5063 if (SynthesizePID) {
5064 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5065 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005066 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005067 }
5068
5069 // FIXME: OBJCGC: weak & strong
5070}
5071
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005072/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005073/// Another legacy compatibility encoding: 32-bit longs are encoded as
5074/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005075/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5076///
5077void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005078 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005079 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005080 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005081 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005082 else
Jay Foad39c79802011-01-12 09:06:06 +00005083 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005084 PointeeTy = IntTy;
5085 }
5086 }
5087}
5088
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005089void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005090 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005091 // We follow the behavior of gcc, expanding structures which are
5092 // directly pointed to, and expanding embedded structures. Note that
5093 // these rules are sufficient to prevent recursive encoding of the
5094 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005095 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005096 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005097}
5098
John McCall393a78d2012-12-20 02:45:14 +00005099static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5100 BuiltinType::Kind kind) {
5101 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005102 case BuiltinType::Void: return 'v';
5103 case BuiltinType::Bool: return 'B';
5104 case BuiltinType::Char_U:
5105 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005106 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005107 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005108 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005109 case BuiltinType::UInt: return 'I';
5110 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005111 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005112 case BuiltinType::UInt128: return 'T';
5113 case BuiltinType::ULongLong: return 'Q';
5114 case BuiltinType::Char_S:
5115 case BuiltinType::SChar: return 'c';
5116 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005117 case BuiltinType::WChar_S:
5118 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005119 case BuiltinType::Int: return 'i';
5120 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005121 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005122 case BuiltinType::LongLong: return 'q';
5123 case BuiltinType::Int128: return 't';
5124 case BuiltinType::Float: return 'f';
5125 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005126 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005127 case BuiltinType::NullPtr: return '*'; // like char*
5128
5129 case BuiltinType::Half:
5130 // FIXME: potentially need @encodes for these!
5131 return ' ';
5132
5133 case BuiltinType::ObjCId:
5134 case BuiltinType::ObjCClass:
5135 case BuiltinType::ObjCSel:
5136 llvm_unreachable("@encoding ObjC primitive type");
5137
5138 // OpenCL and placeholder types don't need @encodings.
5139 case BuiltinType::OCLImage1d:
5140 case BuiltinType::OCLImage1dArray:
5141 case BuiltinType::OCLImage1dBuffer:
5142 case BuiltinType::OCLImage2d:
5143 case BuiltinType::OCLImage2dArray:
5144 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005145 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005146 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005147 case BuiltinType::Dependent:
5148#define BUILTIN_TYPE(KIND, ID)
5149#define PLACEHOLDER_TYPE(KIND, ID) \
5150 case BuiltinType::KIND:
5151#include "clang/AST/BuiltinTypes.def"
5152 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005153 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005154 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005155}
5156
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005157static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5158 EnumDecl *Enum = ET->getDecl();
5159
5160 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5161 if (!Enum->isFixed())
5162 return 'i';
5163
5164 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005165 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5166 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005167}
5168
Jay Foad39c79802011-01-12 09:06:06 +00005169static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005170 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005171 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005172 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005173 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5174 // The GNU runtime requires more information; bitfields are encoded as b,
5175 // then the offset (in bits) of the first element, then the type of the
5176 // bitfield, then the size in bits. For example, in this structure:
5177 //
5178 // struct
5179 // {
5180 // int integer;
5181 // int flags:2;
5182 // };
5183 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5184 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5185 // information is not especially sensible, but we're stuck with it for
5186 // compatibility with GCC, although providing it breaks anything that
5187 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005188 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005189 const RecordDecl *RD = FD->getParent();
5190 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005191 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005192 if (const EnumType *ET = T->getAs<EnumType>())
5193 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005194 else {
5195 const BuiltinType *BT = T->castAs<BuiltinType>();
5196 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5197 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005198 }
Richard Smithcaf33902011-10-10 18:28:20 +00005199 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005200}
5201
Daniel Dunbar07d07852009-10-18 21:17:35 +00005202// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005203void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5204 bool ExpandPointedToStructures,
5205 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005206 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005207 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005208 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005209 bool StructField,
5210 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005211 bool EncodeClassNames,
5212 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005213 CanQualType CT = getCanonicalType(T);
5214 switch (CT->getTypeClass()) {
5215 case Type::Builtin:
5216 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005217 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005218 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005219 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5220 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5221 else
5222 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005223 return;
Mike Stump11289f42009-09-09 15:08:12 +00005224
John McCall393a78d2012-12-20 02:45:14 +00005225 case Type::Complex: {
5226 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005227 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005228 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005229 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005230 return;
5231 }
John McCall393a78d2012-12-20 02:45:14 +00005232
5233 case Type::Atomic: {
5234 const AtomicType *AT = T->castAs<AtomicType>();
5235 S += 'A';
5236 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5237 false, false);
5238 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005239 }
John McCall393a78d2012-12-20 02:45:14 +00005240
5241 // encoding for pointer or reference types.
5242 case Type::Pointer:
5243 case Type::LValueReference:
5244 case Type::RValueReference: {
5245 QualType PointeeTy;
5246 if (isa<PointerType>(CT)) {
5247 const PointerType *PT = T->castAs<PointerType>();
5248 if (PT->isObjCSelType()) {
5249 S += ':';
5250 return;
5251 }
5252 PointeeTy = PT->getPointeeType();
5253 } else {
5254 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5255 }
5256
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005257 bool isReadOnly = false;
5258 // For historical/compatibility reasons, the read-only qualifier of the
5259 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5260 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005261 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005262 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005263 if (OutermostType && T.isConstQualified()) {
5264 isReadOnly = true;
5265 S += 'r';
5266 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005267 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005268 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005269 while (P->getAs<PointerType>())
5270 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005271 if (P.isConstQualified()) {
5272 isReadOnly = true;
5273 S += 'r';
5274 }
5275 }
5276 if (isReadOnly) {
5277 // Another legacy compatibility encoding. Some ObjC qualifier and type
5278 // combinations need to be rearranged.
5279 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005280 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005281 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005282 }
Mike Stump11289f42009-09-09 15:08:12 +00005283
Anders Carlssond8499822007-10-29 05:01:08 +00005284 if (PointeeTy->isCharType()) {
5285 // char pointer types should be encoded as '*' unless it is a
5286 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005287 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005288 S += '*';
5289 return;
5290 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005291 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005292 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5293 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5294 S += '#';
5295 return;
5296 }
5297 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5298 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5299 S += '@';
5300 return;
5301 }
5302 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005303 }
Anders Carlssond8499822007-10-29 05:01:08 +00005304 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005305 getLegacyIntegralTypeEncoding(PointeeTy);
5306
Mike Stump11289f42009-09-09 15:08:12 +00005307 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005308 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005309 return;
5310 }
John McCall393a78d2012-12-20 02:45:14 +00005311
5312 case Type::ConstantArray:
5313 case Type::IncompleteArray:
5314 case Type::VariableArray: {
5315 const ArrayType *AT = cast<ArrayType>(CT);
5316
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005317 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005318 // Incomplete arrays are encoded as a pointer to the array element.
5319 S += '^';
5320
Mike Stump11289f42009-09-09 15:08:12 +00005321 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005322 false, ExpandStructures, FD);
5323 } else {
5324 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005325
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005326 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5327 S += llvm::utostr(CAT->getSize().getZExtValue());
5328 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005329 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005330 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5331 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005332 S += '0';
5333 }
Mike Stump11289f42009-09-09 15:08:12 +00005334
5335 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005336 false, ExpandStructures, FD);
5337 S += ']';
5338 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005339 return;
5340 }
Mike Stump11289f42009-09-09 15:08:12 +00005341
John McCall393a78d2012-12-20 02:45:14 +00005342 case Type::FunctionNoProto:
5343 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005344 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005345 return;
Mike Stump11289f42009-09-09 15:08:12 +00005346
John McCall393a78d2012-12-20 02:45:14 +00005347 case Type::Record: {
5348 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005349 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005350 // Anonymous structures print as '?'
5351 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5352 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005353 if (ClassTemplateSpecializationDecl *Spec
5354 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5355 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005356 llvm::raw_string_ostream OS(S);
5357 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005358 TemplateArgs.data(),
5359 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005360 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005361 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005362 } else {
5363 S += '?';
5364 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005365 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005366 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005367 if (!RDecl->isUnion()) {
5368 getObjCEncodingForStructureImpl(RDecl, S, FD);
5369 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005370 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005371 if (FD) {
5372 S += '"';
5373 S += Field->getNameAsString();
5374 S += '"';
5375 }
Mike Stump11289f42009-09-09 15:08:12 +00005376
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005377 // Special case bit-fields.
5378 if (Field->isBitField()) {
5379 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005380 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005381 } else {
5382 QualType qt = Field->getType();
5383 getLegacyIntegralTypeEncoding(qt);
5384 getObjCEncodingForTypeImpl(qt, S, false, true,
5385 FD, /*OutermostType*/false,
5386 /*EncodingProperty*/false,
5387 /*StructField*/true);
5388 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005389 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005390 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005391 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005392 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005393 return;
5394 }
Mike Stump11289f42009-09-09 15:08:12 +00005395
John McCall393a78d2012-12-20 02:45:14 +00005396 case Type::BlockPointer: {
5397 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005398 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005399 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005400 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005401
5402 S += '<';
5403 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005404 getObjCEncodingForTypeImpl(
5405 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5406 FD, false /* OutermostType */, EncodingProperty,
5407 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005408 // Block self
5409 S += "@?";
5410 // Block parameters
5411 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005412 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5413 E = FPT->param_type_end();
5414 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005415 getObjCEncodingForTypeImpl(*I, S,
5416 ExpandPointedToStructures,
5417 ExpandStructures,
5418 FD,
5419 false /* OutermostType */,
5420 EncodingProperty,
5421 false /* StructField */,
5422 EncodeBlockParameters,
5423 EncodeClassNames);
5424 }
5425 }
5426 S += '>';
5427 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005428 return;
5429 }
Mike Stump11289f42009-09-09 15:08:12 +00005430
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005431 case Type::ObjCObject: {
5432 // hack to match legacy encoding of *id and *Class
5433 QualType Ty = getObjCObjectPointerType(CT);
5434 if (Ty->isObjCIdType()) {
5435 S += "{objc_object=}";
5436 return;
5437 }
5438 else if (Ty->isObjCClassType()) {
5439 S += "{objc_class=}";
5440 return;
5441 }
5442 }
5443
John McCall393a78d2012-12-20 02:45:14 +00005444 case Type::ObjCInterface: {
5445 // Ignore protocol qualifiers when mangling at this level.
5446 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005447
John McCall393a78d2012-12-20 02:45:14 +00005448 // The assumption seems to be that this assert will succeed
5449 // because nested levels will have filtered out 'id' and 'Class'.
5450 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005451 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005452 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005453 S += '{';
5454 const IdentifierInfo *II = OI->getIdentifier();
5455 S += II->getName();
5456 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005457 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005458 DeepCollectObjCIvars(OI, true, Ivars);
5459 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005460 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005461 if (Field->isBitField())
5462 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005463 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005464 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5465 false, false, false, false, false,
5466 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005467 }
5468 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005469 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005470 }
Mike Stump11289f42009-09-09 15:08:12 +00005471
John McCall393a78d2012-12-20 02:45:14 +00005472 case Type::ObjCObjectPointer: {
5473 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005474 if (OPT->isObjCIdType()) {
5475 S += '@';
5476 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005477 }
Mike Stump11289f42009-09-09 15:08:12 +00005478
Steve Narofff0c86112009-10-28 22:03:49 +00005479 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5480 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5481 // Since this is a binary compatibility issue, need to consult with runtime
5482 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005483 S += '#';
5484 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005485 }
Mike Stump11289f42009-09-09 15:08:12 +00005486
Chris Lattnere7cabb92009-07-13 00:10:46 +00005487 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005488 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005489 ExpandPointedToStructures,
5490 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005491 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005492 // Note that we do extended encoding of protocol qualifer list
5493 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005494 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005495 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5496 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005497 S += '<';
5498 S += (*I)->getNameAsString();
5499 S += '>';
5500 }
5501 S += '"';
5502 }
5503 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005504 }
Mike Stump11289f42009-09-09 15:08:12 +00005505
Chris Lattnere7cabb92009-07-13 00:10:46 +00005506 QualType PointeeTy = OPT->getPointeeType();
5507 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005508 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5509 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005510 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005511 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005512 // {...};
5513 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005514 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005515 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005516 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5517 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5518 DeepCollectObjCIvars(OI, true, Ivars);
5519 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5520 if (cast<FieldDecl>(Ivars[i]) == FD) {
5521 S += '{';
5522 S += OI->getIdentifier()->getName();
5523 S += '}';
5524 return;
5525 }
5526 }
5527 }
Mike Stump11289f42009-09-09 15:08:12 +00005528 getObjCEncodingForTypeImpl(PointeeTy, S,
5529 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005530 NULL,
5531 false, false, false, false, false,
5532 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005533 return;
5534 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005535
5536 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005537 if (OPT->getInterfaceDecl() &&
5538 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005539 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005540 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005541 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5542 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005543 S += '<';
5544 S += (*I)->getNameAsString();
5545 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005546 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005547 S += '"';
5548 }
5549 return;
5550 }
Mike Stump11289f42009-09-09 15:08:12 +00005551
John McCalla9e6e8d2010-05-17 23:56:34 +00005552 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005553 // FIXME: we shoul do better than that. 'M' is available.
5554 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005555 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005556
John McCall393a78d2012-12-20 02:45:14 +00005557 case Type::Vector:
5558 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005559 // This matches gcc's encoding, even though technically it is
5560 // insufficient.
5561 // FIXME. We should do a better job than gcc.
5562 return;
John McCall393a78d2012-12-20 02:45:14 +00005563
Richard Smith27d807c2013-04-30 13:56:41 +00005564 case Type::Auto:
5565 // We could see an undeduced auto type here during error recovery.
5566 // Just ignore it.
5567 return;
5568
John McCall393a78d2012-12-20 02:45:14 +00005569#define ABSTRACT_TYPE(KIND, BASE)
5570#define TYPE(KIND, BASE)
5571#define DEPENDENT_TYPE(KIND, BASE) \
5572 case Type::KIND:
5573#define NON_CANONICAL_TYPE(KIND, BASE) \
5574 case Type::KIND:
5575#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5576 case Type::KIND:
5577#include "clang/AST/TypeNodes.def"
5578 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005579 }
John McCall393a78d2012-12-20 02:45:14 +00005580 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005581}
5582
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005583void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5584 std::string &S,
5585 const FieldDecl *FD,
5586 bool includeVBases) const {
5587 assert(RDecl && "Expected non-null RecordDecl");
5588 assert(!RDecl->isUnion() && "Should not be called for unions");
5589 if (!RDecl->getDefinition())
5590 return;
5591
5592 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5593 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5594 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5595
5596 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005597 for (const auto &BI : CXXRec->bases()) {
5598 if (!BI.isVirtual()) {
5599 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005600 if (base->isEmpty())
5601 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005602 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005603 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5604 std::make_pair(offs, base));
5605 }
5606 }
5607 }
5608
5609 unsigned i = 0;
5610 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5611 FieldEnd = RDecl->field_end();
5612 Field != FieldEnd; ++Field, ++i) {
5613 uint64_t offs = layout.getFieldOffset(i);
5614 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005615 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005616 }
5617
5618 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005619 for (const auto &BI : CXXRec->vbases()) {
5620 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005621 if (base->isEmpty())
5622 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005623 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005624 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5625 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005626 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5627 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005628 }
5629 }
5630
5631 CharUnits size;
5632 if (CXXRec) {
5633 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5634 } else {
5635 size = layout.getSize();
5636 }
5637
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005638#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005639 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005640#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005641 std::multimap<uint64_t, NamedDecl *>::iterator
5642 CurLayObj = FieldOrBaseOffsets.begin();
5643
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005644 if (CXXRec && CXXRec->isDynamicClass() &&
5645 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005646 if (FD) {
5647 S += "\"_vptr$";
5648 std::string recname = CXXRec->getNameAsString();
5649 if (recname.empty()) recname = "?";
5650 S += recname;
5651 S += '"';
5652 }
5653 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005654#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005655 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005656#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005657 }
5658
5659 if (!RDecl->hasFlexibleArrayMember()) {
5660 // Mark the end of the structure.
5661 uint64_t offs = toBits(size);
5662 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5663 std::make_pair(offs, (NamedDecl*)0));
5664 }
5665
5666 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005667#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005668 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005669 if (CurOffs < CurLayObj->first) {
5670 uint64_t padding = CurLayObj->first - CurOffs;
5671 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5672 // packing/alignment of members is different that normal, in which case
5673 // the encoding will be out-of-sync with the real layout.
5674 // If the runtime switches to just consider the size of types without
5675 // taking into account alignment, we could make padding explicit in the
5676 // encoding (e.g. using arrays of chars). The encoding strings would be
5677 // longer then though.
5678 CurOffs += padding;
5679 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005680#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005681
5682 NamedDecl *dcl = CurLayObj->second;
5683 if (dcl == 0)
5684 break; // reached end of structure.
5685
5686 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5687 // We expand the bases without their virtual bases since those are going
5688 // in the initial structure. Note that this differs from gcc which
5689 // expands virtual bases each time one is encountered in the hierarchy,
5690 // making the encoding type bigger than it really is.
5691 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005692 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005693#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005694 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005695#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005696 } else {
5697 FieldDecl *field = cast<FieldDecl>(dcl);
5698 if (FD) {
5699 S += '"';
5700 S += field->getNameAsString();
5701 S += '"';
5702 }
5703
5704 if (field->isBitField()) {
5705 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005706#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005707 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005708#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005709 } else {
5710 QualType qt = field->getType();
5711 getLegacyIntegralTypeEncoding(qt);
5712 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5713 /*OutermostType*/false,
5714 /*EncodingProperty*/false,
5715 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005716#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005717 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005718#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005719 }
5720 }
5721 }
5722}
5723
Mike Stump11289f42009-09-09 15:08:12 +00005724void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005725 std::string& S) const {
5726 if (QT & Decl::OBJC_TQ_In)
5727 S += 'n';
5728 if (QT & Decl::OBJC_TQ_Inout)
5729 S += 'N';
5730 if (QT & Decl::OBJC_TQ_Out)
5731 S += 'o';
5732 if (QT & Decl::OBJC_TQ_Bycopy)
5733 S += 'O';
5734 if (QT & Decl::OBJC_TQ_Byref)
5735 S += 'R';
5736 if (QT & Decl::OBJC_TQ_Oneway)
5737 S += 'V';
5738}
5739
Douglas Gregor3ea72692011-08-12 05:46:01 +00005740TypedefDecl *ASTContext::getObjCIdDecl() const {
5741 if (!ObjCIdDecl) {
5742 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5743 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005744 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005745 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005746 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005747}
5748
Douglas Gregor52e02802011-08-12 06:17:30 +00005749TypedefDecl *ASTContext::getObjCSelDecl() const {
5750 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005751 QualType T = getPointerType(ObjCBuiltinSelTy);
5752 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005753 }
5754 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005755}
5756
Douglas Gregor0a586182011-08-12 05:59:41 +00005757TypedefDecl *ASTContext::getObjCClassDecl() const {
5758 if (!ObjCClassDecl) {
5759 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5760 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005761 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005762 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005763 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005764}
5765
Douglas Gregord53ae832012-01-17 18:09:05 +00005766ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5767 if (!ObjCProtocolClassDecl) {
5768 ObjCProtocolClassDecl
5769 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5770 SourceLocation(),
5771 &Idents.get("Protocol"),
5772 /*PrevDecl=*/0,
5773 SourceLocation(), true);
5774 }
5775
5776 return ObjCProtocolClassDecl;
5777}
5778
Meador Inge5d3fb222012-06-16 03:34:49 +00005779//===----------------------------------------------------------------------===//
5780// __builtin_va_list Construction Functions
5781//===----------------------------------------------------------------------===//
5782
5783static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5784 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005785 QualType T = Context->getPointerType(Context->CharTy);
5786 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005787}
5788
5789static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5790 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005791 QualType T = Context->getPointerType(Context->VoidTy);
5792 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005793}
5794
Tim Northover9bb857a2013-01-31 12:13:10 +00005795static TypedefDecl *
5796CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005797 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005798 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005799 if (Context->getLangOpts().CPlusPlus) {
5800 // namespace std { struct __va_list {
5801 NamespaceDecl *NS;
5802 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5803 Context->getTranslationUnitDecl(),
5804 /*Inline*/false, SourceLocation(),
5805 SourceLocation(), &Context->Idents.get("std"),
5806 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005807 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005808 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005809 }
5810
5811 VaListTagDecl->startDefinition();
5812
5813 const size_t NumFields = 5;
5814 QualType FieldTypes[NumFields];
5815 const char *FieldNames[NumFields];
5816
5817 // void *__stack;
5818 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5819 FieldNames[0] = "__stack";
5820
5821 // void *__gr_top;
5822 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5823 FieldNames[1] = "__gr_top";
5824
5825 // void *__vr_top;
5826 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5827 FieldNames[2] = "__vr_top";
5828
5829 // int __gr_offs;
5830 FieldTypes[3] = Context->IntTy;
5831 FieldNames[3] = "__gr_offs";
5832
5833 // int __vr_offs;
5834 FieldTypes[4] = Context->IntTy;
5835 FieldNames[4] = "__vr_offs";
5836
5837 // Create fields
5838 for (unsigned i = 0; i < NumFields; ++i) {
5839 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5840 VaListTagDecl,
5841 SourceLocation(),
5842 SourceLocation(),
5843 &Context->Idents.get(FieldNames[i]),
5844 FieldTypes[i], /*TInfo=*/0,
5845 /*BitWidth=*/0,
5846 /*Mutable=*/false,
5847 ICIS_NoInit);
5848 Field->setAccess(AS_public);
5849 VaListTagDecl->addDecl(Field);
5850 }
5851 VaListTagDecl->completeDefinition();
5852 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5853 Context->VaListTagTy = VaListTagType;
5854
5855 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005856 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005857}
5858
Meador Inge5d3fb222012-06-16 03:34:49 +00005859static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5860 // typedef struct __va_list_tag {
5861 RecordDecl *VaListTagDecl;
5862
Alp Toker2dea15b2013-12-17 01:22:38 +00005863 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005864 VaListTagDecl->startDefinition();
5865
5866 const size_t NumFields = 5;
5867 QualType FieldTypes[NumFields];
5868 const char *FieldNames[NumFields];
5869
5870 // unsigned char gpr;
5871 FieldTypes[0] = Context->UnsignedCharTy;
5872 FieldNames[0] = "gpr";
5873
5874 // unsigned char fpr;
5875 FieldTypes[1] = Context->UnsignedCharTy;
5876 FieldNames[1] = "fpr";
5877
5878 // unsigned short reserved;
5879 FieldTypes[2] = Context->UnsignedShortTy;
5880 FieldNames[2] = "reserved";
5881
5882 // void* overflow_arg_area;
5883 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5884 FieldNames[3] = "overflow_arg_area";
5885
5886 // void* reg_save_area;
5887 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5888 FieldNames[4] = "reg_save_area";
5889
5890 // Create fields
5891 for (unsigned i = 0; i < NumFields; ++i) {
5892 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5893 SourceLocation(),
5894 SourceLocation(),
5895 &Context->Idents.get(FieldNames[i]),
5896 FieldTypes[i], /*TInfo=*/0,
5897 /*BitWidth=*/0,
5898 /*Mutable=*/false,
5899 ICIS_NoInit);
5900 Field->setAccess(AS_public);
5901 VaListTagDecl->addDecl(Field);
5902 }
5903 VaListTagDecl->completeDefinition();
5904 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005905 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005906
5907 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005908 TypedefDecl *VaListTagTypedefDecl =
5909 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5910
Meador Inge5d3fb222012-06-16 03:34:49 +00005911 QualType VaListTagTypedefType =
5912 Context->getTypedefType(VaListTagTypedefDecl);
5913
5914 // typedef __va_list_tag __builtin_va_list[1];
5915 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5916 QualType VaListTagArrayType
5917 = Context->getConstantArrayType(VaListTagTypedefType,
5918 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005919 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005920}
5921
5922static TypedefDecl *
5923CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5924 // typedef struct __va_list_tag {
5925 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005926 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005927 VaListTagDecl->startDefinition();
5928
5929 const size_t NumFields = 4;
5930 QualType FieldTypes[NumFields];
5931 const char *FieldNames[NumFields];
5932
5933 // unsigned gp_offset;
5934 FieldTypes[0] = Context->UnsignedIntTy;
5935 FieldNames[0] = "gp_offset";
5936
5937 // unsigned fp_offset;
5938 FieldTypes[1] = Context->UnsignedIntTy;
5939 FieldNames[1] = "fp_offset";
5940
5941 // void* overflow_arg_area;
5942 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5943 FieldNames[2] = "overflow_arg_area";
5944
5945 // void* reg_save_area;
5946 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5947 FieldNames[3] = "reg_save_area";
5948
5949 // Create fields
5950 for (unsigned i = 0; i < NumFields; ++i) {
5951 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5952 VaListTagDecl,
5953 SourceLocation(),
5954 SourceLocation(),
5955 &Context->Idents.get(FieldNames[i]),
5956 FieldTypes[i], /*TInfo=*/0,
5957 /*BitWidth=*/0,
5958 /*Mutable=*/false,
5959 ICIS_NoInit);
5960 Field->setAccess(AS_public);
5961 VaListTagDecl->addDecl(Field);
5962 }
5963 VaListTagDecl->completeDefinition();
5964 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005965 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005966
5967 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005968 TypedefDecl *VaListTagTypedefDecl =
5969 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5970
Meador Inge5d3fb222012-06-16 03:34:49 +00005971 QualType VaListTagTypedefType =
5972 Context->getTypedefType(VaListTagTypedefDecl);
5973
5974 // typedef __va_list_tag __builtin_va_list[1];
5975 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5976 QualType VaListTagArrayType
5977 = Context->getConstantArrayType(VaListTagTypedefType,
5978 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005979 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005980}
5981
5982static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5983 // typedef int __builtin_va_list[4];
5984 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5985 QualType IntArrayType
5986 = Context->getConstantArrayType(Context->IntTy,
5987 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005988 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005989}
5990
Logan Chien57086ce2012-10-10 06:56:20 +00005991static TypedefDecl *
5992CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005993 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005994 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005995 if (Context->getLangOpts().CPlusPlus) {
5996 // namespace std { struct __va_list {
5997 NamespaceDecl *NS;
5998 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5999 Context->getTranslationUnitDecl(),
6000 /*Inline*/false, SourceLocation(),
6001 SourceLocation(), &Context->Idents.get("std"),
6002 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006003 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006004 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006005 }
6006
6007 VaListDecl->startDefinition();
6008
6009 // void * __ap;
6010 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6011 VaListDecl,
6012 SourceLocation(),
6013 SourceLocation(),
6014 &Context->Idents.get("__ap"),
6015 Context->getPointerType(Context->VoidTy),
6016 /*TInfo=*/0,
6017 /*BitWidth=*/0,
6018 /*Mutable=*/false,
6019 ICIS_NoInit);
6020 Field->setAccess(AS_public);
6021 VaListDecl->addDecl(Field);
6022
6023 // };
6024 VaListDecl->completeDefinition();
6025
6026 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006027 QualType T = Context->getRecordType(VaListDecl);
6028 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006029}
6030
Ulrich Weigand47445072013-05-06 16:26:41 +00006031static TypedefDecl *
6032CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6033 // typedef struct __va_list_tag {
6034 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006035 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006036 VaListTagDecl->startDefinition();
6037
6038 const size_t NumFields = 4;
6039 QualType FieldTypes[NumFields];
6040 const char *FieldNames[NumFields];
6041
6042 // long __gpr;
6043 FieldTypes[0] = Context->LongTy;
6044 FieldNames[0] = "__gpr";
6045
6046 // long __fpr;
6047 FieldTypes[1] = Context->LongTy;
6048 FieldNames[1] = "__fpr";
6049
6050 // void *__overflow_arg_area;
6051 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6052 FieldNames[2] = "__overflow_arg_area";
6053
6054 // void *__reg_save_area;
6055 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6056 FieldNames[3] = "__reg_save_area";
6057
6058 // Create fields
6059 for (unsigned i = 0; i < NumFields; ++i) {
6060 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6061 VaListTagDecl,
6062 SourceLocation(),
6063 SourceLocation(),
6064 &Context->Idents.get(FieldNames[i]),
6065 FieldTypes[i], /*TInfo=*/0,
6066 /*BitWidth=*/0,
6067 /*Mutable=*/false,
6068 ICIS_NoInit);
6069 Field->setAccess(AS_public);
6070 VaListTagDecl->addDecl(Field);
6071 }
6072 VaListTagDecl->completeDefinition();
6073 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6074 Context->VaListTagTy = VaListTagType;
6075
6076 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006077 TypedefDecl *VaListTagTypedefDecl =
6078 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006079 QualType VaListTagTypedefType =
6080 Context->getTypedefType(VaListTagTypedefDecl);
6081
6082 // typedef __va_list_tag __builtin_va_list[1];
6083 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6084 QualType VaListTagArrayType
6085 = Context->getConstantArrayType(VaListTagTypedefType,
6086 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006087
Alp Toker56b5cc92013-12-15 10:36:26 +00006088 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006089}
6090
Meador Inge5d3fb222012-06-16 03:34:49 +00006091static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6092 TargetInfo::BuiltinVaListKind Kind) {
6093 switch (Kind) {
6094 case TargetInfo::CharPtrBuiltinVaList:
6095 return CreateCharPtrBuiltinVaListDecl(Context);
6096 case TargetInfo::VoidPtrBuiltinVaList:
6097 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006098 case TargetInfo::AArch64ABIBuiltinVaList:
6099 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006100 case TargetInfo::PowerABIBuiltinVaList:
6101 return CreatePowerABIBuiltinVaListDecl(Context);
6102 case TargetInfo::X86_64ABIBuiltinVaList:
6103 return CreateX86_64ABIBuiltinVaListDecl(Context);
6104 case TargetInfo::PNaClABIBuiltinVaList:
6105 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006106 case TargetInfo::AAPCSABIBuiltinVaList:
6107 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006108 case TargetInfo::SystemZBuiltinVaList:
6109 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006110 }
6111
6112 llvm_unreachable("Unhandled __builtin_va_list type kind");
6113}
6114
6115TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006116 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006117 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006118 assert(BuiltinVaListDecl->isImplicit());
6119 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006120
6121 return BuiltinVaListDecl;
6122}
6123
Meador Ingecfb60902012-07-01 15:57:25 +00006124QualType ASTContext::getVaListTagType() const {
6125 // Force the creation of VaListTagTy by building the __builtin_va_list
6126 // declaration.
6127 if (VaListTagTy.isNull())
6128 (void) getBuiltinVaListDecl();
6129
6130 return VaListTagTy;
6131}
6132
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006133void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006134 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006135 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006136
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006137 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006138}
6139
John McCalld28ae272009-12-02 08:04:21 +00006140/// \brief Retrieve the template name that corresponds to a non-empty
6141/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006142TemplateName
6143ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6144 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006145 unsigned size = End - Begin;
6146 assert(size > 1 && "set is not overloaded!");
6147
6148 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6149 size * sizeof(FunctionTemplateDecl*));
6150 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6151
6152 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006153 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006154 NamedDecl *D = *I;
6155 assert(isa<FunctionTemplateDecl>(D) ||
6156 (isa<UsingShadowDecl>(D) &&
6157 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6158 *Storage++ = D;
6159 }
6160
6161 return TemplateName(OT);
6162}
6163
Douglas Gregordc572a32009-03-30 22:58:21 +00006164/// \brief Retrieve the template name that represents a qualified
6165/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006166TemplateName
6167ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6168 bool TemplateKeyword,
6169 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006170 assert(NNS && "Missing nested-name-specifier in qualified template name");
6171
Douglas Gregorc42075a2010-02-04 18:10:26 +00006172 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006173 llvm::FoldingSetNodeID ID;
6174 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6175
6176 void *InsertPos = 0;
6177 QualifiedTemplateName *QTN =
6178 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6179 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006180 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6181 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006182 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6183 }
6184
6185 return TemplateName(QTN);
6186}
6187
6188/// \brief Retrieve the template name that represents a dependent
6189/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006190TemplateName
6191ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6192 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006193 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006194 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006195
6196 llvm::FoldingSetNodeID ID;
6197 DependentTemplateName::Profile(ID, NNS, Name);
6198
6199 void *InsertPos = 0;
6200 DependentTemplateName *QTN =
6201 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6202
6203 if (QTN)
6204 return TemplateName(QTN);
6205
6206 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6207 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006208 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6209 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006210 } else {
6211 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006212 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6213 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006214 DependentTemplateName *CheckQTN =
6215 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6216 assert(!CheckQTN && "Dependent type name canonicalization broken");
6217 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006218 }
6219
6220 DependentTemplateNames.InsertNode(QTN, InsertPos);
6221 return TemplateName(QTN);
6222}
6223
Douglas Gregor71395fa2009-11-04 00:56:37 +00006224/// \brief Retrieve the template name that represents a dependent
6225/// template name such as \c MetaFun::template operator+.
6226TemplateName
6227ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006228 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006229 assert((!NNS || NNS->isDependent()) &&
6230 "Nested name specifier must be dependent");
6231
6232 llvm::FoldingSetNodeID ID;
6233 DependentTemplateName::Profile(ID, NNS, Operator);
6234
6235 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006236 DependentTemplateName *QTN
6237 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006238
6239 if (QTN)
6240 return TemplateName(QTN);
6241
6242 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6243 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006244 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6245 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006246 } else {
6247 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006248 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6249 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006250
6251 DependentTemplateName *CheckQTN
6252 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6253 assert(!CheckQTN && "Dependent template name canonicalization broken");
6254 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006255 }
6256
6257 DependentTemplateNames.InsertNode(QTN, InsertPos);
6258 return TemplateName(QTN);
6259}
6260
Douglas Gregor5590be02011-01-15 06:45:20 +00006261TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006262ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6263 TemplateName replacement) const {
6264 llvm::FoldingSetNodeID ID;
6265 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6266
6267 void *insertPos = 0;
6268 SubstTemplateTemplateParmStorage *subst
6269 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6270
6271 if (!subst) {
6272 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6273 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6274 }
6275
6276 return TemplateName(subst);
6277}
6278
6279TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006280ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6281 const TemplateArgument &ArgPack) const {
6282 ASTContext &Self = const_cast<ASTContext &>(*this);
6283 llvm::FoldingSetNodeID ID;
6284 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6285
6286 void *InsertPos = 0;
6287 SubstTemplateTemplateParmPackStorage *Subst
6288 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6289
6290 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006291 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006292 ArgPack.pack_size(),
6293 ArgPack.pack_begin());
6294 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6295 }
6296
6297 return TemplateName(Subst);
6298}
6299
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006300/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006301/// TargetInfo, produce the corresponding type. The unsigned @p Type
6302/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006303CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006304 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006305 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006306 case TargetInfo::SignedChar: return SignedCharTy;
6307 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006308 case TargetInfo::SignedShort: return ShortTy;
6309 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6310 case TargetInfo::SignedInt: return IntTy;
6311 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6312 case TargetInfo::SignedLong: return LongTy;
6313 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6314 case TargetInfo::SignedLongLong: return LongLongTy;
6315 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6316 }
6317
David Blaikie83d382b2011-09-23 05:06:16 +00006318 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006319}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006320
6321//===----------------------------------------------------------------------===//
6322// Type Predicates.
6323//===----------------------------------------------------------------------===//
6324
Fariborz Jahanian96207692009-02-18 21:49:28 +00006325/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6326/// garbage collection attribute.
6327///
John McCall553d45a2011-01-12 00:34:59 +00006328Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006329 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006330 return Qualifiers::GCNone;
6331
David Blaikiebbafb8a2012-03-11 07:00:24 +00006332 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006333 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6334
6335 // Default behaviour under objective-C's gc is for ObjC pointers
6336 // (or pointers to them) be treated as though they were declared
6337 // as __strong.
6338 if (GCAttrs == Qualifiers::GCNone) {
6339 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6340 return Qualifiers::Strong;
6341 else if (Ty->isPointerType())
6342 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6343 } else {
6344 // It's not valid to set GC attributes on anything that isn't a
6345 // pointer.
6346#ifndef NDEBUG
6347 QualType CT = Ty->getCanonicalTypeInternal();
6348 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6349 CT = AT->getElementType();
6350 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6351#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006352 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006353 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006354}
6355
Chris Lattner49af6a42008-04-07 06:51:04 +00006356//===----------------------------------------------------------------------===//
6357// Type Compatibility Testing
6358//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006359
Mike Stump11289f42009-09-09 15:08:12 +00006360/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006361/// compatible.
6362static bool areCompatVectorTypes(const VectorType *LHS,
6363 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006364 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006365 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006366 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006367}
6368
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006369bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6370 QualType SecondVec) {
6371 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6372 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6373
6374 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6375 return true;
6376
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006377 // Treat Neon vector types and most AltiVec vector types as if they are the
6378 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006379 const VectorType *First = FirstVec->getAs<VectorType>();
6380 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006381 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006382 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006383 First->getVectorKind() != VectorType::AltiVecPixel &&
6384 First->getVectorKind() != VectorType::AltiVecBool &&
6385 Second->getVectorKind() != VectorType::AltiVecPixel &&
6386 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006387 return true;
6388
6389 return false;
6390}
6391
Steve Naroff8e6aee52009-07-23 01:01:38 +00006392//===----------------------------------------------------------------------===//
6393// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6394//===----------------------------------------------------------------------===//
6395
6396/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6397/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006398bool
6399ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6400 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006401 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006402 return true;
6403 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6404 E = rProto->protocol_end(); PI != E; ++PI)
6405 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6406 return true;
6407 return false;
6408}
6409
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006410/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6411/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006412bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6413 QualType rhs) {
6414 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6415 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6416 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6417
6418 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6419 E = lhsQID->qual_end(); I != E; ++I) {
6420 bool match = false;
6421 ObjCProtocolDecl *lhsProto = *I;
6422 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6423 E = rhsOPT->qual_end(); J != E; ++J) {
6424 ObjCProtocolDecl *rhsProto = *J;
6425 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6426 match = true;
6427 break;
6428 }
6429 }
6430 if (!match)
6431 return false;
6432 }
6433 return true;
6434}
6435
Steve Naroff8e6aee52009-07-23 01:01:38 +00006436/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6437/// ObjCQualifiedIDType.
6438bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6439 bool compare) {
6440 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006441 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006442 lhs->isObjCIdType() || lhs->isObjCClassType())
6443 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006444 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006445 rhs->isObjCIdType() || rhs->isObjCClassType())
6446 return true;
6447
6448 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006449 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006450
Steve Naroff8e6aee52009-07-23 01:01:38 +00006451 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006452
Steve Naroff8e6aee52009-07-23 01:01:38 +00006453 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006454 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006455 // make sure we check the class hierarchy.
6456 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6457 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6458 E = lhsQID->qual_end(); I != E; ++I) {
6459 // when comparing an id<P> on lhs with a static type on rhs,
6460 // see if static class implements all of id's protocols, directly or
6461 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006462 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006463 return false;
6464 }
6465 }
6466 // If there are no qualifiers and no interface, we have an 'id'.
6467 return true;
6468 }
Mike Stump11289f42009-09-09 15:08:12 +00006469 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006470 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6471 E = lhsQID->qual_end(); I != E; ++I) {
6472 ObjCProtocolDecl *lhsProto = *I;
6473 bool match = false;
6474
6475 // when comparing an id<P> on lhs with a static type on rhs,
6476 // see if static class implements all of id's protocols, directly or
6477 // through its super class and categories.
6478 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6479 E = rhsOPT->qual_end(); J != E; ++J) {
6480 ObjCProtocolDecl *rhsProto = *J;
6481 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6482 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6483 match = true;
6484 break;
6485 }
6486 }
Mike Stump11289f42009-09-09 15:08:12 +00006487 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006488 // make sure we check the class hierarchy.
6489 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6490 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6491 E = lhsQID->qual_end(); I != E; ++I) {
6492 // when comparing an id<P> on lhs with a static type on rhs,
6493 // see if static class implements all of id's protocols, directly or
6494 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006495 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006496 match = true;
6497 break;
6498 }
6499 }
6500 }
6501 if (!match)
6502 return false;
6503 }
Mike Stump11289f42009-09-09 15:08:12 +00006504
Steve Naroff8e6aee52009-07-23 01:01:38 +00006505 return true;
6506 }
Mike Stump11289f42009-09-09 15:08:12 +00006507
Steve Naroff8e6aee52009-07-23 01:01:38 +00006508 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6509 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6510
Mike Stump11289f42009-09-09 15:08:12 +00006511 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006512 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006513 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006514 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6515 E = lhsOPT->qual_end(); I != E; ++I) {
6516 ObjCProtocolDecl *lhsProto = *I;
6517 bool match = false;
6518
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006519 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006520 // see if static class implements all of id's protocols, directly or
6521 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006522 // First, lhs protocols in the qualifier list must be found, direct
6523 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006524 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6525 E = rhsQID->qual_end(); J != E; ++J) {
6526 ObjCProtocolDecl *rhsProto = *J;
6527 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6528 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6529 match = true;
6530 break;
6531 }
6532 }
6533 if (!match)
6534 return false;
6535 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006536
6537 // Static class's protocols, or its super class or category protocols
6538 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6539 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6540 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6541 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6542 // This is rather dubious but matches gcc's behavior. If lhs has
6543 // no type qualifier and its class has no static protocol(s)
6544 // assume that it is mismatch.
6545 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6546 return false;
6547 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6548 LHSInheritedProtocols.begin(),
6549 E = LHSInheritedProtocols.end(); I != E; ++I) {
6550 bool match = false;
6551 ObjCProtocolDecl *lhsProto = (*I);
6552 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6553 E = rhsQID->qual_end(); J != E; ++J) {
6554 ObjCProtocolDecl *rhsProto = *J;
6555 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6556 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6557 match = true;
6558 break;
6559 }
6560 }
6561 if (!match)
6562 return false;
6563 }
6564 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006565 return true;
6566 }
6567 return false;
6568}
6569
Eli Friedman47f77112008-08-22 00:56:42 +00006570/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006571/// compatible for assignment from RHS to LHS. This handles validation of any
6572/// protocol qualifiers on the LHS or RHS.
6573///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006574bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6575 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006576 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6577 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6578
Steve Naroff1329fa02009-07-15 18:40:39 +00006579 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006580 if (LHS->isObjCUnqualifiedIdOrClass() ||
6581 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006582 return true;
6583
John McCall8b07ec22010-05-15 11:32:37 +00006584 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006585 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6586 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006587 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006588
6589 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6590 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6591 QualType(RHSOPT,0));
6592
John McCall8b07ec22010-05-15 11:32:37 +00006593 // If we have 2 user-defined types, fall into that path.
6594 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006595 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006596
Steve Naroff8e6aee52009-07-23 01:01:38 +00006597 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006598}
6599
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006600/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006601/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006602/// arguments in block literals. When passed as arguments, passing 'A*' where
6603/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6604/// not OK. For the return type, the opposite is not OK.
6605bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6606 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006607 const ObjCObjectPointerType *RHSOPT,
6608 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006609 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006610 return true;
6611
6612 if (LHSOPT->isObjCBuiltinType()) {
6613 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6614 }
6615
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006616 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006617 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6618 QualType(RHSOPT,0),
6619 false);
6620
6621 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6622 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6623 if (LHS && RHS) { // We have 2 user-defined types.
6624 if (LHS != RHS) {
6625 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006626 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006627 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006628 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006629 }
6630 else
6631 return true;
6632 }
6633 return false;
6634}
6635
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006636/// getIntersectionOfProtocols - This routine finds the intersection of set
6637/// of protocols inherited from two distinct objective-c pointer objects.
6638/// It is used to build composite qualifier list of the composite type of
6639/// the conditional expression involving two objective-c pointer objects.
6640static
6641void getIntersectionOfProtocols(ASTContext &Context,
6642 const ObjCObjectPointerType *LHSOPT,
6643 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006644 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006645
John McCall8b07ec22010-05-15 11:32:37 +00006646 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6647 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6648 assert(LHS->getInterface() && "LHS must have an interface base");
6649 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006650
6651 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6652 unsigned LHSNumProtocols = LHS->getNumProtocols();
6653 if (LHSNumProtocols > 0)
6654 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6655 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006656 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006657 Context.CollectInheritedProtocols(LHS->getInterface(),
6658 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006659 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6660 LHSInheritedProtocols.end());
6661 }
6662
6663 unsigned RHSNumProtocols = RHS->getNumProtocols();
6664 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006665 ObjCProtocolDecl **RHSProtocols =
6666 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006667 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6668 if (InheritedProtocolSet.count(RHSProtocols[i]))
6669 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006670 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006671 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006672 Context.CollectInheritedProtocols(RHS->getInterface(),
6673 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006674 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6675 RHSInheritedProtocols.begin(),
6676 E = RHSInheritedProtocols.end(); I != E; ++I)
6677 if (InheritedProtocolSet.count((*I)))
6678 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006679 }
6680}
6681
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006682/// areCommonBaseCompatible - Returns common base class of the two classes if
6683/// one found. Note that this is O'2 algorithm. But it will be called as the
6684/// last type comparison in a ?-exp of ObjC pointer types before a
6685/// warning is issued. So, its invokation is extremely rare.
6686QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006687 const ObjCObjectPointerType *Lptr,
6688 const ObjCObjectPointerType *Rptr) {
6689 const ObjCObjectType *LHS = Lptr->getObjectType();
6690 const ObjCObjectType *RHS = Rptr->getObjectType();
6691 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6692 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006693 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006694 return QualType();
6695
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006696 do {
John McCall8b07ec22010-05-15 11:32:37 +00006697 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006698 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006699 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006700 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6701
6702 QualType Result = QualType(LHS, 0);
6703 if (!Protocols.empty())
6704 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6705 Result = getObjCObjectPointerType(Result);
6706 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006707 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006708 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006709
6710 return QualType();
6711}
6712
John McCall8b07ec22010-05-15 11:32:37 +00006713bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6714 const ObjCObjectType *RHS) {
6715 assert(LHS->getInterface() && "LHS is not an interface type");
6716 assert(RHS->getInterface() && "RHS is not an interface type");
6717
Chris Lattner49af6a42008-04-07 06:51:04 +00006718 // Verify that the base decls are compatible: the RHS must be a subclass of
6719 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006720 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006721 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006722
Chris Lattner49af6a42008-04-07 06:51:04 +00006723 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6724 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006725 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006726 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006727
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006728 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6729 // more detailed analysis is required.
6730 if (RHS->getNumProtocols() == 0) {
6731 // OK, if LHS is a superclass of RHS *and*
6732 // this superclass is assignment compatible with LHS.
6733 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006734 bool IsSuperClass =
6735 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6736 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006737 // OK if conversion of LHS to SuperClass results in narrowing of types
6738 // ; i.e., SuperClass may implement at least one of the protocols
6739 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6740 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6741 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006742 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006743 // If super class has no protocols, it is not a match.
6744 if (SuperClassInheritedProtocols.empty())
6745 return false;
6746
6747 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6748 LHSPE = LHS->qual_end();
6749 LHSPI != LHSPE; LHSPI++) {
6750 bool SuperImplementsProtocol = false;
6751 ObjCProtocolDecl *LHSProto = (*LHSPI);
6752
6753 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6754 SuperClassInheritedProtocols.begin(),
6755 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6756 ObjCProtocolDecl *SuperClassProto = (*I);
6757 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6758 SuperImplementsProtocol = true;
6759 break;
6760 }
6761 }
6762 if (!SuperImplementsProtocol)
6763 return false;
6764 }
6765 return true;
6766 }
6767 return false;
6768 }
Mike Stump11289f42009-09-09 15:08:12 +00006769
John McCall8b07ec22010-05-15 11:32:37 +00006770 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6771 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006772 LHSPI != LHSPE; LHSPI++) {
6773 bool RHSImplementsProtocol = false;
6774
6775 // If the RHS doesn't implement the protocol on the left, the types
6776 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006777 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6778 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006779 RHSPI != RHSPE; RHSPI++) {
6780 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006781 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006782 break;
6783 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006784 }
6785 // FIXME: For better diagnostics, consider passing back the protocol name.
6786 if (!RHSImplementsProtocol)
6787 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006788 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006789 // The RHS implements all protocols listed on the LHS.
6790 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006791}
6792
Steve Naroffb7605152009-02-12 17:52:19 +00006793bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6794 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006795 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6796 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006797
Steve Naroff7cae42b2009-07-10 23:34:53 +00006798 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006799 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006800
6801 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6802 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006803}
6804
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006805bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6806 return canAssignObjCInterfaces(
6807 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6808 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6809}
6810
Mike Stump11289f42009-09-09 15:08:12 +00006811/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006812/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006813/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006814/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006815bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6816 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006817 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006818 return hasSameType(LHS, RHS);
6819
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006820 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006821}
6822
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006823bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006824 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006825}
6826
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006827bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6828 return !mergeTypes(LHS, RHS, true).isNull();
6829}
6830
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006831/// mergeTransparentUnionType - if T is a transparent union type and a member
6832/// of T is compatible with SubType, return the merged type, else return
6833/// QualType()
6834QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6835 bool OfBlockPointer,
6836 bool Unqualified) {
6837 if (const RecordType *UT = T->getAsUnionType()) {
6838 RecordDecl *UD = UT->getDecl();
6839 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006840 for (const auto *I : UD->fields()) {
6841 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006842 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6843 if (!MT.isNull())
6844 return MT;
6845 }
6846 }
6847 }
6848
6849 return QualType();
6850}
6851
Alp Toker9cacbab2014-01-20 20:26:09 +00006852/// mergeFunctionParameterTypes - merge two types which appear as function
6853/// parameter types
6854QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6855 bool OfBlockPointer,
6856 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006857 // GNU extension: two types are compatible if they appear as a function
6858 // argument, one of the types is a transparent union type and the other
6859 // type is compatible with a union member
6860 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6861 Unqualified);
6862 if (!lmerge.isNull())
6863 return lmerge;
6864
6865 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6866 Unqualified);
6867 if (!rmerge.isNull())
6868 return rmerge;
6869
6870 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6871}
6872
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006873QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006874 bool OfBlockPointer,
6875 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006876 const FunctionType *lbase = lhs->getAs<FunctionType>();
6877 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006878 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6879 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006880 bool allLTypes = true;
6881 bool allRTypes = true;
6882
6883 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006884 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006885 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006886 QualType RHS = rbase->getReturnType();
6887 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006888 bool UnqualifiedResult = Unqualified;
6889 if (!UnqualifiedResult)
6890 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006891 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006892 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006893 else
Alp Toker314cc812014-01-25 16:55:45 +00006894 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006895 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006896 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006897
6898 if (Unqualified)
6899 retType = retType.getUnqualifiedType();
6900
Alp Toker314cc812014-01-25 16:55:45 +00006901 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6902 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006903 if (Unqualified) {
6904 LRetType = LRetType.getUnqualifiedType();
6905 RRetType = RRetType.getUnqualifiedType();
6906 }
6907
6908 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006909 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006910 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006911 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006912
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006913 // FIXME: double check this
6914 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6915 // rbase->getRegParmAttr() != 0 &&
6916 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006917 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6918 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006919
Douglas Gregor8c940862010-01-18 17:14:39 +00006920 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006921 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006922 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006923
John McCall8c6b56f2010-12-15 01:06:38 +00006924 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006925 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6926 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006927 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6928 return QualType();
6929
John McCall31168b02011-06-15 23:02:42 +00006930 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6931 return QualType();
6932
John McCall8c6b56f2010-12-15 01:06:38 +00006933 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6934 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006935
Rafael Espindola8778c282012-11-29 16:09:03 +00006936 if (lbaseInfo.getNoReturn() != NoReturn)
6937 allLTypes = false;
6938 if (rbaseInfo.getNoReturn() != NoReturn)
6939 allRTypes = false;
6940
John McCall31168b02011-06-15 23:02:42 +00006941 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006942
Eli Friedman47f77112008-08-22 00:56:42 +00006943 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006944 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6945 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006946 // Compatible functions must have the same number of parameters
6947 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006948 return QualType();
6949
6950 // Variadic and non-variadic functions aren't compatible
6951 if (lproto->isVariadic() != rproto->isVariadic())
6952 return QualType();
6953
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006954 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6955 return QualType();
6956
Fariborz Jahanian97676972011-09-28 21:52:05 +00006957 if (LangOpts.ObjCAutoRefCount &&
6958 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6959 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006960
6961 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006962 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006963 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6964 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6965 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6966 QualType paramType = mergeFunctionParameterTypes(
6967 lParamType, rParamType, OfBlockPointer, Unqualified);
6968 if (paramType.isNull())
6969 return QualType();
6970
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006971 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006972 paramType = paramType.getUnqualifiedType();
6973
6974 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006975 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006976 lParamType = lParamType.getUnqualifiedType();
6977 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006978 }
Alp Toker601b22c2014-01-21 23:35:24 +00006979
6980 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006981 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006982 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006983 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006984 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006985
Eli Friedman47f77112008-08-22 00:56:42 +00006986 if (allLTypes) return lhs;
6987 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006988
6989 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6990 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006991 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006992 }
6993
6994 if (lproto) allRTypes = false;
6995 if (rproto) allLTypes = false;
6996
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006997 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006998 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006999 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007000 if (proto->isVariadic()) return QualType();
7001 // Check that the types are compatible with the types that
7002 // would result from default argument promotions (C99 6.7.5.3p15).
7003 // The only types actually affected are promotable integer
7004 // types and floats, which would be passed as a different
7005 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007006 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7007 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007008
Eli Friedman448ce402012-08-30 00:44:15 +00007009 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007010 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007011 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7012 paramTy = Enum->getDecl()->getIntegerType();
7013 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007014 return QualType();
7015 }
Alp Toker601b22c2014-01-21 23:35:24 +00007016
7017 if (paramTy->isPromotableIntegerType() ||
7018 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007019 return QualType();
7020 }
7021
7022 if (allLTypes) return lhs;
7023 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007024
7025 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7026 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007027 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007028 }
7029
7030 if (allLTypes) return lhs;
7031 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007032 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007033}
7034
John McCall433c2e62013-03-21 00:10:07 +00007035/// Given that we have an enum type and a non-enum type, try to merge them.
7036static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7037 QualType other, bool isBlockReturnType) {
7038 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7039 // a signed integer type, or an unsigned integer type.
7040 // Compatibility is based on the underlying type, not the promotion
7041 // type.
7042 QualType underlyingType = ET->getDecl()->getIntegerType();
7043 if (underlyingType.isNull()) return QualType();
7044 if (Context.hasSameType(underlyingType, other))
7045 return other;
7046
7047 // In block return types, we're more permissive and accept any
7048 // integral type of the same size.
7049 if (isBlockReturnType && other->isIntegerType() &&
7050 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7051 return other;
7052
7053 return QualType();
7054}
7055
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007056QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007057 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007058 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007059 // C++ [expr]: If an expression initially has the type "reference to T", the
7060 // type is adjusted to "T" prior to any further analysis, the expression
7061 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007062 // expression is an lvalue unless the reference is an rvalue reference and
7063 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007064 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7065 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007066
7067 if (Unqualified) {
7068 LHS = LHS.getUnqualifiedType();
7069 RHS = RHS.getUnqualifiedType();
7070 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007071
Eli Friedman47f77112008-08-22 00:56:42 +00007072 QualType LHSCan = getCanonicalType(LHS),
7073 RHSCan = getCanonicalType(RHS);
7074
7075 // If two types are identical, they are compatible.
7076 if (LHSCan == RHSCan)
7077 return LHS;
7078
John McCall8ccfcb52009-09-24 19:53:00 +00007079 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007080 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7081 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007082 if (LQuals != RQuals) {
7083 // If any of these qualifiers are different, we have a type
7084 // mismatch.
7085 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007086 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7087 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007088 return QualType();
7089
7090 // Exactly one GC qualifier difference is allowed: __strong is
7091 // okay if the other type has no GC qualifier but is an Objective
7092 // C object pointer (i.e. implicitly strong by default). We fix
7093 // this by pretending that the unqualified type was actually
7094 // qualified __strong.
7095 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7096 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7097 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7098
7099 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7100 return QualType();
7101
7102 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7103 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7104 }
7105 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7106 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7107 }
Eli Friedman47f77112008-08-22 00:56:42 +00007108 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007109 }
7110
7111 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007112
Eli Friedmandcca6332009-06-01 01:22:52 +00007113 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7114 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007115
Chris Lattnerfd652912008-01-14 05:45:46 +00007116 // We want to consider the two function types to be the same for these
7117 // comparisons, just force one to the other.
7118 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7119 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007120
7121 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007122 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7123 LHSClass = Type::ConstantArray;
7124 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7125 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007126
John McCall8b07ec22010-05-15 11:32:37 +00007127 // ObjCInterfaces are just specialized ObjCObjects.
7128 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7129 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7130
Nate Begemance4d7fc2008-04-18 23:10:10 +00007131 // Canonicalize ExtVector -> Vector.
7132 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7133 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007134
Chris Lattner95554662008-04-07 05:43:21 +00007135 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007136 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007137 // Note that we only have special rules for turning block enum
7138 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007139 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007140 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007141 }
John McCall9dd450b2009-09-21 23:43:11 +00007142 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007143 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007144 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007145 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007146 if (OfBlockPointer && !BlockReturnType) {
7147 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7148 return LHS;
7149 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7150 return RHS;
7151 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007152
Eli Friedman47f77112008-08-22 00:56:42 +00007153 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007154 }
Eli Friedman47f77112008-08-22 00:56:42 +00007155
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007156 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007157 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007158#define TYPE(Class, Base)
7159#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007160#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007161#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7162#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7163#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007164 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007165
Richard Smith27d807c2013-04-30 13:56:41 +00007166 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007167 case Type::LValueReference:
7168 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007169 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007170 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007171
John McCall8b07ec22010-05-15 11:32:37 +00007172 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007173 case Type::IncompleteArray:
7174 case Type::VariableArray:
7175 case Type::FunctionProto:
7176 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007177 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007178
Chris Lattnerfd652912008-01-14 05:45:46 +00007179 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007180 {
7181 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007182 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7183 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007184 if (Unqualified) {
7185 LHSPointee = LHSPointee.getUnqualifiedType();
7186 RHSPointee = RHSPointee.getUnqualifiedType();
7187 }
7188 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7189 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007190 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007191 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007192 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007193 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007194 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007195 return getPointerType(ResultType);
7196 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007197 case Type::BlockPointer:
7198 {
7199 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007200 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7201 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007202 if (Unqualified) {
7203 LHSPointee = LHSPointee.getUnqualifiedType();
7204 RHSPointee = RHSPointee.getUnqualifiedType();
7205 }
7206 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7207 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007208 if (ResultType.isNull()) return QualType();
7209 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7210 return LHS;
7211 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7212 return RHS;
7213 return getBlockPointerType(ResultType);
7214 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007215 case Type::Atomic:
7216 {
7217 // Merge two pointer types, while trying to preserve typedef info
7218 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7219 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7220 if (Unqualified) {
7221 LHSValue = LHSValue.getUnqualifiedType();
7222 RHSValue = RHSValue.getUnqualifiedType();
7223 }
7224 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7225 Unqualified);
7226 if (ResultType.isNull()) return QualType();
7227 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7228 return LHS;
7229 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7230 return RHS;
7231 return getAtomicType(ResultType);
7232 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007233 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007234 {
7235 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7236 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7237 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7238 return QualType();
7239
7240 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7241 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007242 if (Unqualified) {
7243 LHSElem = LHSElem.getUnqualifiedType();
7244 RHSElem = RHSElem.getUnqualifiedType();
7245 }
7246
7247 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007248 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007249 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7250 return LHS;
7251 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7252 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007253 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7254 ArrayType::ArraySizeModifier(), 0);
7255 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7256 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007257 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7258 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007259 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7260 return LHS;
7261 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7262 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007263 if (LVAT) {
7264 // FIXME: This isn't correct! But tricky to implement because
7265 // the array's size has to be the size of LHS, but the type
7266 // has to be different.
7267 return LHS;
7268 }
7269 if (RVAT) {
7270 // FIXME: This isn't correct! But tricky to implement because
7271 // the array's size has to be the size of RHS, but the type
7272 // has to be different.
7273 return RHS;
7274 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007275 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7276 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007277 return getIncompleteArrayType(ResultType,
7278 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007279 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007280 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007281 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007282 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007283 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007284 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007285 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007286 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007287 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007288 case Type::Complex:
7289 // Distinct complex types are incompatible.
7290 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007291 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007292 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007293 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7294 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007295 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007296 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007297 case Type::ObjCObject: {
7298 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007299 // FIXME: This should be type compatibility, e.g. whether
7300 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007301 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7302 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7303 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007304 return LHS;
7305
Eli Friedman47f77112008-08-22 00:56:42 +00007306 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007307 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007308 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007309 if (OfBlockPointer) {
7310 if (canAssignObjCInterfacesInBlockPointer(
7311 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007312 RHS->getAs<ObjCObjectPointerType>(),
7313 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007314 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007315 return QualType();
7316 }
John McCall9dd450b2009-09-21 23:43:11 +00007317 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7318 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007319 return LHS;
7320
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007321 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007322 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007323 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007324
David Blaikie8a40f702012-01-17 06:56:22 +00007325 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007326}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007327
Fariborz Jahanian97676972011-09-28 21:52:05 +00007328bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7329 const FunctionProtoType *FromFunctionType,
7330 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007331 if (FromFunctionType->hasAnyConsumedParams() !=
7332 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007333 return false;
7334 FunctionProtoType::ExtProtoInfo FromEPI =
7335 FromFunctionType->getExtProtoInfo();
7336 FunctionProtoType::ExtProtoInfo ToEPI =
7337 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007338 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007339 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7340 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007341 return false;
7342 }
7343 return true;
7344}
7345
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007346/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7347/// 'RHS' attributes and returns the merged version; including for function
7348/// return types.
7349QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7350 QualType LHSCan = getCanonicalType(LHS),
7351 RHSCan = getCanonicalType(RHS);
7352 // If two types are identical, they are compatible.
7353 if (LHSCan == RHSCan)
7354 return LHS;
7355 if (RHSCan->isFunctionType()) {
7356 if (!LHSCan->isFunctionType())
7357 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007358 QualType OldReturnType =
7359 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007360 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007361 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007362 QualType ResReturnType =
7363 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7364 if (ResReturnType.isNull())
7365 return QualType();
7366 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7367 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7368 // In either case, use OldReturnType to build the new function type.
7369 const FunctionType *F = LHS->getAs<FunctionType>();
7370 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007371 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7372 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007373 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007374 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007375 return ResultType;
7376 }
7377 }
7378 return QualType();
7379 }
7380
7381 // If the qualifiers are different, the types can still be merged.
7382 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7383 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7384 if (LQuals != RQuals) {
7385 // If any of these qualifiers are different, we have a type mismatch.
7386 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7387 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7388 return QualType();
7389
7390 // Exactly one GC qualifier difference is allowed: __strong is
7391 // okay if the other type has no GC qualifier but is an Objective
7392 // C object pointer (i.e. implicitly strong by default). We fix
7393 // this by pretending that the unqualified type was actually
7394 // qualified __strong.
7395 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7396 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7397 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7398
7399 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7400 return QualType();
7401
7402 if (GC_L == Qualifiers::Strong)
7403 return LHS;
7404 if (GC_R == Qualifiers::Strong)
7405 return RHS;
7406 return QualType();
7407 }
7408
7409 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7410 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7411 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7412 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7413 if (ResQT == LHSBaseQT)
7414 return LHS;
7415 if (ResQT == RHSBaseQT)
7416 return RHS;
7417 }
7418 return QualType();
7419}
7420
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007421//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007422// Integer Predicates
7423//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007424
Jay Foad39c79802011-01-12 09:06:06 +00007425unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007426 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007427 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007428 if (T->isBooleanType())
7429 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007430 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007431 return (unsigned)getTypeSize(T);
7432}
7433
Abramo Bagnara13640492012-09-09 10:21:24 +00007434QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007435 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007436
7437 // Turn <4 x signed int> -> <4 x unsigned int>
7438 if (const VectorType *VTy = T->getAs<VectorType>())
7439 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007440 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007441
7442 // For enums, we return the unsigned version of the base type.
7443 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007444 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007445
7446 const BuiltinType *BTy = T->getAs<BuiltinType>();
7447 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007448 switch (BTy->getKind()) {
7449 case BuiltinType::Char_S:
7450 case BuiltinType::SChar:
7451 return UnsignedCharTy;
7452 case BuiltinType::Short:
7453 return UnsignedShortTy;
7454 case BuiltinType::Int:
7455 return UnsignedIntTy;
7456 case BuiltinType::Long:
7457 return UnsignedLongTy;
7458 case BuiltinType::LongLong:
7459 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007460 case BuiltinType::Int128:
7461 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007462 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007463 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007464 }
7465}
7466
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007467ASTMutationListener::~ASTMutationListener() { }
7468
Richard Smith1fa5d642013-05-11 05:45:24 +00007469void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7470 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007471
7472//===----------------------------------------------------------------------===//
7473// Builtin Type Computation
7474//===----------------------------------------------------------------------===//
7475
7476/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007477/// pointer over the consumed characters. This returns the resultant type. If
7478/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7479/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7480/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007481///
7482/// RequiresICE is filled in on return to indicate whether the value is required
7483/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007484static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007485 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007486 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007487 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007488 // Modifiers.
7489 int HowLong = 0;
7490 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007491 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007492
Chris Lattnerdc226c22010-10-01 22:42:38 +00007493 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007494 bool Done = false;
7495 while (!Done) {
7496 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007497 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007498 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007499 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007500 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007501 case 'S':
7502 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7503 assert(!Signed && "Can't use 'S' modifier multiple times!");
7504 Signed = true;
7505 break;
7506 case 'U':
7507 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7508 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7509 Unsigned = true;
7510 break;
7511 case 'L':
7512 assert(HowLong <= 2 && "Can't have LLLL modifier");
7513 ++HowLong;
7514 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007515 case 'W':
7516 // This modifier represents int64 type.
7517 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7518 switch (Context.getTargetInfo().getInt64Type()) {
7519 default:
7520 llvm_unreachable("Unexpected integer type");
7521 case TargetInfo::SignedLong:
7522 HowLong = 1;
7523 break;
7524 case TargetInfo::SignedLongLong:
7525 HowLong = 2;
7526 break;
7527 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007528 }
7529 }
7530
7531 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007532
Chris Lattnerecd79c62009-06-14 00:45:47 +00007533 // Read the base type.
7534 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007535 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007536 case 'v':
7537 assert(HowLong == 0 && !Signed && !Unsigned &&
7538 "Bad modifiers used with 'v'!");
7539 Type = Context.VoidTy;
7540 break;
Jack Carter24bef982013-08-15 15:16:57 +00007541 case 'h':
7542 assert(HowLong == 0 && !Signed && !Unsigned &&
7543 "Bad modifiers used with 'f'!");
7544 Type = Context.HalfTy;
7545 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007546 case 'f':
7547 assert(HowLong == 0 && !Signed && !Unsigned &&
7548 "Bad modifiers used with 'f'!");
7549 Type = Context.FloatTy;
7550 break;
7551 case 'd':
7552 assert(HowLong < 2 && !Signed && !Unsigned &&
7553 "Bad modifiers used with 'd'!");
7554 if (HowLong)
7555 Type = Context.LongDoubleTy;
7556 else
7557 Type = Context.DoubleTy;
7558 break;
7559 case 's':
7560 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7561 if (Unsigned)
7562 Type = Context.UnsignedShortTy;
7563 else
7564 Type = Context.ShortTy;
7565 break;
7566 case 'i':
7567 if (HowLong == 3)
7568 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7569 else if (HowLong == 2)
7570 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7571 else if (HowLong == 1)
7572 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7573 else
7574 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7575 break;
7576 case 'c':
7577 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7578 if (Signed)
7579 Type = Context.SignedCharTy;
7580 else if (Unsigned)
7581 Type = Context.UnsignedCharTy;
7582 else
7583 Type = Context.CharTy;
7584 break;
7585 case 'b': // boolean
7586 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7587 Type = Context.BoolTy;
7588 break;
7589 case 'z': // size_t.
7590 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7591 Type = Context.getSizeType();
7592 break;
7593 case 'F':
7594 Type = Context.getCFConstantStringType();
7595 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007596 case 'G':
7597 Type = Context.getObjCIdType();
7598 break;
7599 case 'H':
7600 Type = Context.getObjCSelType();
7601 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007602 case 'M':
7603 Type = Context.getObjCSuperType();
7604 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007605 case 'a':
7606 Type = Context.getBuiltinVaListType();
7607 assert(!Type.isNull() && "builtin va list type not initialized!");
7608 break;
7609 case 'A':
7610 // This is a "reference" to a va_list; however, what exactly
7611 // this means depends on how va_list is defined. There are two
7612 // different kinds of va_list: ones passed by value, and ones
7613 // passed by reference. An example of a by-value va_list is
7614 // x86, where va_list is a char*. An example of by-ref va_list
7615 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7616 // we want this argument to be a char*&; for x86-64, we want
7617 // it to be a __va_list_tag*.
7618 Type = Context.getBuiltinVaListType();
7619 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007620 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007621 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007622 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007623 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007624 break;
7625 case 'V': {
7626 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007627 unsigned NumElements = strtoul(Str, &End, 10);
7628 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007629 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007630
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007631 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7632 RequiresICE, false);
7633 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007634
7635 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007636 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007637 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007638 break;
7639 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007640 case 'E': {
7641 char *End;
7642
7643 unsigned NumElements = strtoul(Str, &End, 10);
7644 assert(End != Str && "Missing vector size");
7645
7646 Str = End;
7647
7648 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7649 false);
7650 Type = Context.getExtVectorType(ElementType, NumElements);
7651 break;
7652 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007653 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007654 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7655 false);
7656 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007657 Type = Context.getComplexType(ElementType);
7658 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007659 }
7660 case 'Y' : {
7661 Type = Context.getPointerDiffType();
7662 break;
7663 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007664 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007665 Type = Context.getFILEType();
7666 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007667 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007668 return QualType();
7669 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007670 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007671 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007672 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007673 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007674 else
7675 Type = Context.getjmp_bufType();
7676
Mike Stump2adb4da2009-07-28 23:47:15 +00007677 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007678 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007679 return QualType();
7680 }
7681 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007682 case 'K':
7683 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7684 Type = Context.getucontext_tType();
7685
7686 if (Type.isNull()) {
7687 Error = ASTContext::GE_Missing_ucontext;
7688 return QualType();
7689 }
7690 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007691 case 'p':
7692 Type = Context.getProcessIDType();
7693 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007694 }
Mike Stump11289f42009-09-09 15:08:12 +00007695
Chris Lattnerdc226c22010-10-01 22:42:38 +00007696 // If there are modifiers and if we're allowed to parse them, go for it.
7697 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007698 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007699 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007700 default: Done = true; --Str; break;
7701 case '*':
7702 case '&': {
7703 // Both pointers and references can have their pointee types
7704 // qualified with an address space.
7705 char *End;
7706 unsigned AddrSpace = strtoul(Str, &End, 10);
7707 if (End != Str && AddrSpace != 0) {
7708 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7709 Str = End;
7710 }
7711 if (c == '*')
7712 Type = Context.getPointerType(Type);
7713 else
7714 Type = Context.getLValueReferenceType(Type);
7715 break;
7716 }
7717 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7718 case 'C':
7719 Type = Type.withConst();
7720 break;
7721 case 'D':
7722 Type = Context.getVolatileType(Type);
7723 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007724 case 'R':
7725 Type = Type.withRestrict();
7726 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007727 }
7728 }
Chris Lattner84733392010-10-01 07:13:18 +00007729
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007730 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007731 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007732
Chris Lattnerecd79c62009-06-14 00:45:47 +00007733 return Type;
7734}
7735
7736/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007737QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007738 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007739 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007740 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007741
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007742 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007743
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007744 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007745 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007746 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7747 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007748 if (Error != GE_None)
7749 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007750
7751 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7752
Chris Lattnerecd79c62009-06-14 00:45:47 +00007753 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007754 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007755 if (Error != GE_None)
7756 return QualType();
7757
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007758 // If this argument is required to be an IntegerConstantExpression and the
7759 // caller cares, fill in the bitmask we return.
7760 if (RequiresICE && IntegerConstantArgs)
7761 *IntegerConstantArgs |= 1 << ArgTypes.size();
7762
Chris Lattnerecd79c62009-06-14 00:45:47 +00007763 // Do array -> pointer decay. The builtin should use the decayed type.
7764 if (Ty->isArrayType())
7765 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007766
Chris Lattnerecd79c62009-06-14 00:45:47 +00007767 ArgTypes.push_back(Ty);
7768 }
7769
7770 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7771 "'.' should only occur at end of builtin type list!");
7772
Reid Kleckner78af0702013-08-27 23:08:25 +00007773 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007774 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7775
7776 bool Variadic = (TypeStr[0] == '.');
7777
7778 // We really shouldn't be making a no-proto type here, especially in C++.
7779 if (ArgTypes.empty() && Variadic)
7780 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007781
John McCalldb40c7f2010-12-14 08:05:40 +00007782 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007783 EPI.ExtInfo = EI;
7784 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007785
Jordan Rose5c382722013-03-08 21:51:21 +00007786 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007787}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007788
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007789GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007790 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007791 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007792
Rafael Espindola3ae00052013-05-13 00:12:11 +00007793 GVALinkage External = GVA_StrongExternal;
7794 switch (FD->getTemplateSpecializationKind()) {
7795 case TSK_Undeclared:
7796 case TSK_ExplicitSpecialization:
7797 External = GVA_StrongExternal;
7798 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007799
Rafael Espindola3ae00052013-05-13 00:12:11 +00007800 case TSK_ExplicitInstantiationDefinition:
7801 return GVA_ExplicitTemplateInstantiation;
7802
7803 case TSK_ExplicitInstantiationDeclaration:
7804 case TSK_ImplicitInstantiation:
7805 External = GVA_TemplateInstantiation;
7806 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007807 }
7808
7809 if (!FD->isInlined())
7810 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007811
Alp Tokerbfa39342014-01-14 12:51:41 +00007812 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007813 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007814 // GNU or C99 inline semantics. Determine whether this symbol should be
7815 // externally visible.
7816 if (FD->isInlineDefinitionExternallyVisible())
7817 return External;
7818
7819 // C99 inline semantics, where the symbol is not externally visible.
7820 return GVA_C99Inline;
7821 }
7822
7823 // C++0x [temp.explicit]p9:
7824 // [ Note: The intent is that an inline function that is the subject of
7825 // an explicit instantiation declaration will still be implicitly
7826 // instantiated when used so that the body can be considered for
7827 // inlining, but that no out-of-line copy of the inline function would be
7828 // generated in the translation unit. -- end note ]
7829 if (FD->getTemplateSpecializationKind()
7830 == TSK_ExplicitInstantiationDeclaration)
7831 return GVA_C99Inline;
7832
7833 return GVA_CXXInline;
7834}
7835
7836GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007837 if (!VD->isExternallyVisible())
7838 return GVA_Internal;
7839
Richard Smith8809a0c2013-09-27 20:14:12 +00007840 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007841 case TSK_Undeclared:
7842 case TSK_ExplicitSpecialization:
7843 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007844
Rafael Espindola3ae00052013-05-13 00:12:11 +00007845 case TSK_ExplicitInstantiationDeclaration:
7846 llvm_unreachable("Variable should not be instantiated");
7847 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007848
Rafael Espindola3ae00052013-05-13 00:12:11 +00007849 case TSK_ExplicitInstantiationDefinition:
7850 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007851
Rafael Espindola3ae00052013-05-13 00:12:11 +00007852 case TSK_ImplicitInstantiation:
7853 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007854 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007855
7856 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007857}
7858
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007859bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007860 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7861 if (!VD->isFileVarDecl())
7862 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007863 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7864 // We never need to emit an uninstantiated function template.
7865 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7866 return false;
7867 } else
7868 return false;
7869
7870 // If this is a member of a class template, we do not need to emit it.
7871 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007872 return false;
7873
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007874 // Weak references don't produce any output by themselves.
7875 if (D->hasAttr<WeakRefAttr>())
7876 return false;
7877
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007878 // Aliases and used decls are required.
7879 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7880 return true;
7881
7882 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7883 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007884 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007885 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007886
7887 // Constructors and destructors are required.
7888 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7889 return true;
7890
John McCall6bd2a892013-01-25 22:31:03 +00007891 // The key function for a class is required. This rule only comes
7892 // into play when inline functions can be key functions, though.
7893 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7894 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7895 const CXXRecordDecl *RD = MD->getParent();
7896 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7897 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7898 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7899 return true;
7900 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007901 }
7902 }
7903
7904 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7905
7906 // static, static inline, always_inline, and extern inline functions can
7907 // always be deferred. Normal inline functions can be deferred in C99/C++.
7908 // Implicit template instantiations can also be deferred in C++.
7909 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007910 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007911 return false;
7912 return true;
7913 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007914
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007915 const VarDecl *VD = cast<VarDecl>(D);
7916 assert(VD->isFileVarDecl() && "Expected file scoped var");
7917
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007918 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7919 return false;
7920
Richard Smitha0e5e542012-11-12 21:38:00 +00007921 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007922 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007923 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7924 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007925
Richard Smitha0e5e542012-11-12 21:38:00 +00007926 // Variables that have destruction with side-effects are required.
7927 if (VD->getType().isDestructedType())
7928 return true;
7929
7930 // Variables that have initialization with side-effects are required.
7931 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7932 return true;
7933
7934 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007935}
Charles Davis53c59df2010-08-16 03:33:14 +00007936
Reid Kleckner78af0702013-08-27 23:08:25 +00007937CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7938 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007939 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007940 if (IsCXXMethod)
7941 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007942
Reid Kleckner78af0702013-08-27 23:08:25 +00007943 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007944}
7945
Jay Foad39c79802011-01-12 09:06:06 +00007946bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007947 // Pass through to the C++ ABI object
7948 return ABI->isNearlyEmpty(RD);
7949}
7950
Reid Kleckner96f8f932014-02-05 17:27:08 +00007951VTableContextBase *ASTContext::getVTableContext() {
7952 if (!VTContext.get()) {
7953 if (Target->getCXXABI().isMicrosoft())
7954 VTContext.reset(new MicrosoftVTableContext(*this));
7955 else
7956 VTContext.reset(new ItaniumVTableContext(*this));
7957 }
7958 return VTContext.get();
7959}
7960
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007961MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007962 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007963 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007964 case TargetCXXABI::GenericItanium:
7965 case TargetCXXABI::GenericARM:
7966 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007967 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007968 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007969 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007970 }
David Blaikie83d382b2011-09-23 05:06:16 +00007971 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007972}
7973
Charles Davis53c59df2010-08-16 03:33:14 +00007974CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007975
7976size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007977 return ASTRecordLayouts.getMemorySize() +
7978 llvm::capacity_in_bytes(ObjCLayouts) +
7979 llvm::capacity_in_bytes(KeyFunctions) +
7980 llvm::capacity_in_bytes(ObjCImpls) +
7981 llvm::capacity_in_bytes(BlockVarCopyInits) +
7982 llvm::capacity_in_bytes(DeclAttrs) +
7983 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7984 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7985 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7986 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7987 llvm::capacity_in_bytes(OverriddenMethods) +
7988 llvm::capacity_in_bytes(Types) +
7989 llvm::capacity_in_bytes(VariableArrayTypes) +
7990 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007991}
Ted Kremenek540017e2011-10-06 05:00:56 +00007992
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007993/// getIntTypeForBitwidth -
7994/// sets integer QualTy according to specified details:
7995/// bitwidth, signed/unsigned.
7996/// Returns empty type if there is no appropriate target types.
7997QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7998 unsigned Signed) const {
7999 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8000 CanQualType QualTy = getFromTargetType(Ty);
8001 if (!QualTy && DestWidth == 128)
8002 return Signed ? Int128Ty : UnsignedInt128Ty;
8003 return QualTy;
8004}
8005
8006/// getRealTypeForBitwidth -
8007/// sets floating point QualTy according to specified bitwidth.
8008/// Returns empty type if there is no appropriate target types.
8009QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8010 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8011 switch (Ty) {
8012 case TargetInfo::Float:
8013 return FloatTy;
8014 case TargetInfo::Double:
8015 return DoubleTy;
8016 case TargetInfo::LongDouble:
8017 return LongDoubleTy;
8018 case TargetInfo::NoFloat:
8019 return QualType();
8020 }
8021
8022 llvm_unreachable("Unhandled TargetInfo::RealType value");
8023}
8024
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008025void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8026 if (Number > 1)
8027 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008028}
8029
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008030unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8031 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8032 MangleNumbers.find(ND);
8033 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008034}
8035
David Majnemer2206bf52014-03-05 08:57:59 +00008036void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8037 if (Number > 1)
8038 StaticLocalNumbers[VD] = Number;
8039}
8040
8041unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8042 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8043 StaticLocalNumbers.find(VD);
8044 return I != StaticLocalNumbers.end() ? I->second : 1;
8045}
8046
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008047MangleNumberingContext &
8048ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008049 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8050 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8051 if (!MCtx)
8052 MCtx = createMangleNumberingContext();
8053 return *MCtx;
8054}
8055
8056MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8057 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008058}
8059
Ted Kremenek540017e2011-10-06 05:00:56 +00008060void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8061 ParamIndices[D] = index;
8062}
8063
8064unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8065 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8066 assert(I != ParamIndices.end() &&
8067 "ParmIndices lacks entry set by ParmVarDecl");
8068 return I->second;
8069}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008070
Richard Smithe6c01442013-06-05 00:46:14 +00008071APValue *
8072ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8073 bool MayCreate) {
8074 assert(E && E->getStorageDuration() == SD_Static &&
8075 "don't need to cache the computed value for this temporary");
8076 if (MayCreate)
8077 return &MaterializedTemporaryValues[E];
8078
8079 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8080 MaterializedTemporaryValues.find(E);
8081 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8082}
8083
Fariborz Jahanian615de762013-05-28 17:37:39 +00008084bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8085 const llvm::Triple &T = getTargetInfo().getTriple();
8086 if (!T.isOSDarwin())
8087 return false;
8088
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008089 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8090 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8091 return false;
8092
Fariborz Jahanian615de762013-05-28 17:37:39 +00008093 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8094 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8095 uint64_t Size = sizeChars.getQuantity();
8096 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8097 unsigned Align = alignChars.getQuantity();
8098 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8099 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8100}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008101
8102namespace {
8103
8104 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8105 /// parents as defined by the \c RecursiveASTVisitor.
8106 ///
8107 /// Note that the relationship described here is purely in terms of AST
8108 /// traversal - there are other relationships (for example declaration context)
8109 /// in the AST that are better modeled by special matchers.
8110 ///
8111 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8112 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8113
8114 public:
8115 /// \brief Builds and returns the translation unit's parent map.
8116 ///
8117 /// The caller takes ownership of the returned \c ParentMap.
8118 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8119 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8120 Visitor.TraverseDecl(&TU);
8121 return Visitor.Parents;
8122 }
8123
8124 private:
8125 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8126
8127 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8128 }
8129
8130 bool shouldVisitTemplateInstantiations() const {
8131 return true;
8132 }
8133 bool shouldVisitImplicitCode() const {
8134 return true;
8135 }
8136 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8137 // are not triggered during data recursion.
8138 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8139 return false;
8140 }
8141
8142 template <typename T>
8143 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8144 if (Node == NULL)
8145 return true;
8146 if (ParentStack.size() > 0)
8147 // FIXME: Currently we add the same parent multiple times, for example
8148 // when we visit all subexpressions of template instantiations; this is
8149 // suboptimal, bug benign: the only way to visit those is with
8150 // hasAncestor / hasParent, and those do not create new matches.
8151 // The plan is to enable DynTypedNode to be storable in a map or hash
8152 // map. The main problem there is to implement hash functions /
8153 // comparison operators for all types that DynTypedNode supports that
8154 // do not have pointer identity.
8155 (*Parents)[Node].push_back(ParentStack.back());
8156 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8157 bool Result = (this ->* traverse) (Node);
8158 ParentStack.pop_back();
8159 return Result;
8160 }
8161
8162 bool TraverseDecl(Decl *DeclNode) {
8163 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8164 }
8165
8166 bool TraverseStmt(Stmt *StmtNode) {
8167 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8168 }
8169
8170 ASTContext::ParentMap *Parents;
8171 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8172
8173 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8174 };
8175
8176} // end namespace
8177
8178ASTContext::ParentVector
8179ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8180 assert(Node.getMemoizationData() &&
8181 "Invariant broken: only nodes that support memoization may be "
8182 "used in the parent map.");
8183 if (!AllParents) {
8184 // We always need to run over the whole translation unit, as
8185 // hasAncestor can escape any subtree.
8186 AllParents.reset(
8187 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8188 }
8189 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8190 if (I == AllParents->end()) {
8191 return ParentVector();
8192 }
8193 return I->second;
8194}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008195
8196bool
8197ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8198 const ObjCMethodDecl *MethodImpl) {
8199 // No point trying to match an unavailable/deprecated mothod.
8200 if (MethodDecl->hasAttr<UnavailableAttr>()
8201 || MethodDecl->hasAttr<DeprecatedAttr>())
8202 return false;
8203 if (MethodDecl->getObjCDeclQualifier() !=
8204 MethodImpl->getObjCDeclQualifier())
8205 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008206 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008207 return false;
8208
8209 if (MethodDecl->param_size() != MethodImpl->param_size())
8210 return false;
8211
8212 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8213 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8214 EF = MethodDecl->param_end();
8215 IM != EM && IF != EF; ++IM, ++IF) {
8216 const ParmVarDecl *DeclVar = (*IF);
8217 const ParmVarDecl *ImplVar = (*IM);
8218 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8219 return false;
8220 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8221 return false;
8222 }
8223 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8224
8225}