blob: 7d48365f1b1e02fffbe197c099e2bfb3947b7f28 [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.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001816 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001817 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001818 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001819 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001820 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001821 CollectInheritedProtocols(*P, Protocols);
1822 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001823 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001824
1825 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001826 for (ObjCInterfaceDecl::visible_categories_iterator
1827 Cat = OI->visible_categories_begin(),
1828 CatEnd = OI->visible_categories_end();
1829 Cat != CatEnd; ++Cat) {
1830 CollectInheritedProtocols(*Cat, Protocols);
1831 }
1832
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001833 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1834 while (SD) {
1835 CollectInheritedProtocols(SD, Protocols);
1836 SD = SD->getSuperClass();
1837 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001838 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001839 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001840 PE = OC->protocol_end(); P != PE; ++P) {
1841 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001842 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001843 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1844 PE = Proto->protocol_end(); P != PE; ++P)
1845 CollectInheritedProtocols(*P, Protocols);
1846 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001847 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001848 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1849 PE = OP->protocol_end(); P != PE; ++P) {
1850 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001851 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001852 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1853 PE = Proto->protocol_end(); P != PE; ++P)
1854 CollectInheritedProtocols(*P, Protocols);
1855 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001856 }
1857}
1858
Jay Foad39c79802011-01-12 09:06:06 +00001859unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001860 unsigned count = 0;
1861 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001862 for (ObjCInterfaceDecl::known_extensions_iterator
1863 Ext = OI->known_extensions_begin(),
1864 ExtEnd = OI->known_extensions_end();
1865 Ext != ExtEnd; ++Ext) {
1866 count += Ext->ivar_size();
1867 }
1868
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001869 // Count ivar defined in this class's implementation. This
1870 // includes synthesized ivars.
1871 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001872 count += ImplDecl->ivar_size();
1873
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001874 return count;
1875}
1876
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001877bool ASTContext::isSentinelNullExpr(const Expr *E) {
1878 if (!E)
1879 return false;
1880
1881 // nullptr_t is always treated as null.
1882 if (E->getType()->isNullPtrType()) return true;
1883
1884 if (E->getType()->isAnyPointerType() &&
1885 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1886 Expr::NPC_ValueDependentIsNull))
1887 return true;
1888
1889 // Unfortunately, __null has type 'int'.
1890 if (isa<GNUNullExpr>(E)) return true;
1891
1892 return false;
1893}
1894
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001895/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1896ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1897 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1898 I = ObjCImpls.find(D);
1899 if (I != ObjCImpls.end())
1900 return cast<ObjCImplementationDecl>(I->second);
1901 return 0;
1902}
1903/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1904ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1905 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1906 I = ObjCImpls.find(D);
1907 if (I != ObjCImpls.end())
1908 return cast<ObjCCategoryImplDecl>(I->second);
1909 return 0;
1910}
1911
1912/// \brief Set the implementation of ObjCInterfaceDecl.
1913void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1914 ObjCImplementationDecl *ImplD) {
1915 assert(IFaceD && ImplD && "Passed null params");
1916 ObjCImpls[IFaceD] = ImplD;
1917}
1918/// \brief Set the implementation of ObjCCategoryDecl.
1919void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1920 ObjCCategoryImplDecl *ImplD) {
1921 assert(CatD && ImplD && "Passed null params");
1922 ObjCImpls[CatD] = ImplD;
1923}
1924
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001925const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1926 const NamedDecl *ND) const {
1927 if (const ObjCInterfaceDecl *ID =
1928 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001929 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001930 if (const ObjCCategoryDecl *CD =
1931 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001932 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001933 if (const ObjCImplDecl *IMD =
1934 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001935 return IMD->getClassInterface();
1936
1937 return 0;
1938}
1939
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001940/// \brief Get the copy initialization expression of VarDecl,or NULL if
1941/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001942Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001943 assert(VD && "Passed null params");
1944 assert(VD->hasAttr<BlocksAttr>() &&
1945 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001946 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001947 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001948 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1949}
1950
1951/// \brief Set the copy inialization expression of a block var decl.
1952void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1953 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001954 assert(VD->hasAttr<BlocksAttr>() &&
1955 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001956 BlockVarCopyInits[VD] = Init;
1957}
1958
John McCallbcd03502009-12-07 02:54:59 +00001959TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001960 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001961 if (!DataSize)
1962 DataSize = TypeLoc::getFullDataSizeForType(T);
1963 else
1964 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001965 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001966
John McCallbcd03502009-12-07 02:54:59 +00001967 TypeSourceInfo *TInfo =
1968 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1969 new (TInfo) TypeSourceInfo(T);
1970 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001971}
1972
John McCallbcd03502009-12-07 02:54:59 +00001973TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001974 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001975 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001976 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001977 return DI;
1978}
1979
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001980const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001981ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001982 return getObjCLayout(D, 0);
1983}
1984
1985const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001986ASTContext::getASTObjCImplementationLayout(
1987 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001988 return getObjCLayout(D->getClassInterface(), D);
1989}
1990
Chris Lattner983a8bb2007-07-13 22:13:22 +00001991//===----------------------------------------------------------------------===//
1992// Type creation/memoization methods
1993//===----------------------------------------------------------------------===//
1994
Jay Foad39c79802011-01-12 09:06:06 +00001995QualType
John McCall33ddac02011-01-19 10:06:00 +00001996ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1997 unsigned fastQuals = quals.getFastQualifiers();
1998 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001999
2000 // Check if we've already instantiated this type.
2001 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002002 ExtQuals::Profile(ID, baseType, quals);
2003 void *insertPos = 0;
2004 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2005 assert(eq->getQualifiers() == quals);
2006 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002007 }
2008
John McCall33ddac02011-01-19 10:06:00 +00002009 // If the base type is not canonical, make the appropriate canonical type.
2010 QualType canon;
2011 if (!baseType->isCanonicalUnqualified()) {
2012 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002013 canonSplit.Quals.addConsistentQualifiers(quals);
2014 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002015
2016 // Re-find the insert position.
2017 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2018 }
2019
2020 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2021 ExtQualNodes.InsertNode(eq, insertPos);
2022 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002023}
2024
Jay Foad39c79802011-01-12 09:06:06 +00002025QualType
2026ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002027 QualType CanT = getCanonicalType(T);
2028 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002029 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002030
John McCall8ccfcb52009-09-24 19:53:00 +00002031 // If we are composing extended qualifiers together, merge together
2032 // into one ExtQuals node.
2033 QualifierCollector Quals;
2034 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002035
John McCall8ccfcb52009-09-24 19:53:00 +00002036 // If this type already has an address space specified, it cannot get
2037 // another one.
2038 assert(!Quals.hasAddressSpace() &&
2039 "Type cannot be in multiple addr spaces!");
2040 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002041
John McCall8ccfcb52009-09-24 19:53:00 +00002042 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002043}
2044
Chris Lattnerd60183d2009-02-18 22:53:11 +00002045QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002046 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002047 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002048 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002049 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002050
John McCall53fa7142010-12-24 02:08:15 +00002051 if (const PointerType *ptr = T->getAs<PointerType>()) {
2052 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002053 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002054 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2055 return getPointerType(ResultType);
2056 }
2057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
John McCall8ccfcb52009-09-24 19:53:00 +00002059 // If we are composing extended qualifiers together, merge together
2060 // into one ExtQuals node.
2061 QualifierCollector Quals;
2062 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002063
John McCall8ccfcb52009-09-24 19:53:00 +00002064 // If this type already has an ObjCGC specified, it cannot get
2065 // another one.
2066 assert(!Quals.hasObjCGCAttr() &&
2067 "Type cannot have multiple ObjCGCs!");
2068 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002069
John McCall8ccfcb52009-09-24 19:53:00 +00002070 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002071}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002072
John McCall4f5019e2010-12-19 02:44:49 +00002073const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2074 FunctionType::ExtInfo Info) {
2075 if (T->getExtInfo() == Info)
2076 return T;
2077
2078 QualType Result;
2079 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002080 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002081 } else {
2082 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2083 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2084 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002085 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002086 }
2087
2088 return cast<FunctionType>(Result.getTypePtr());
2089}
2090
Richard Smith2a7d4812013-05-04 07:00:32 +00002091void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2092 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002093 FD = FD->getMostRecentDecl();
2094 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002095 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2096 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002097 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002098 if (FunctionDecl *Next = FD->getPreviousDecl())
2099 FD = Next;
2100 else
2101 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002102 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002103 if (ASTMutationListener *L = getASTMutationListener())
2104 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002105}
2106
Chris Lattnerc6395932007-06-22 20:56:16 +00002107/// getComplexType - Return the uniqued reference to the type for a complex
2108/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002109QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002110 // Unique pointers, to guarantee there is only one pointer of a particular
2111 // structure.
2112 llvm::FoldingSetNodeID ID;
2113 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002114
Chris Lattnerc6395932007-06-22 20:56:16 +00002115 void *InsertPos = 0;
2116 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2117 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattnerc6395932007-06-22 20:56:16 +00002119 // If the pointee type isn't canonical, this won't be a canonical type either,
2120 // so fill in the canonical type field.
2121 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002122 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002123 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002124
Chris Lattnerc6395932007-06-22 20:56:16 +00002125 // Get the new insert position for the node we care about.
2126 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002127 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002128 }
John McCall90d1c2d2009-09-24 23:30:46 +00002129 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002130 Types.push_back(New);
2131 ComplexTypes.InsertNode(New, InsertPos);
2132 return QualType(New, 0);
2133}
2134
Chris Lattner970e54e2006-11-12 00:37:36 +00002135/// getPointerType - Return the uniqued reference to the type for a pointer to
2136/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002137QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002138 // Unique pointers, to guarantee there is only one pointer of a particular
2139 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002140 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002141 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002142
Chris Lattner67521df2007-01-27 01:29:36 +00002143 void *InsertPos = 0;
2144 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002145 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattner7ccecb92006-11-12 08:50:50 +00002147 // If the pointee type isn't canonical, this won't be a canonical type either,
2148 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002149 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002150 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002151 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002152
Bob Wilsonc8541f22013-03-15 17:12:43 +00002153 // Get the new insert position for the node we care about.
2154 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2155 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2156 }
John McCall90d1c2d2009-09-24 23:30:46 +00002157 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002158 Types.push_back(New);
2159 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002160 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002161}
2162
Reid Kleckner0503a872013-12-05 01:23:43 +00002163QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2164 llvm::FoldingSetNodeID ID;
2165 AdjustedType::Profile(ID, Orig, New);
2166 void *InsertPos = 0;
2167 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2168 if (AT)
2169 return QualType(AT, 0);
2170
2171 QualType Canonical = getCanonicalType(New);
2172
2173 // Get the new insert position for the node we care about.
2174 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2175 assert(AT == 0 && "Shouldn't be in the map!");
2176
2177 AT = new (*this, TypeAlignment)
2178 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2179 Types.push_back(AT);
2180 AdjustedTypes.InsertNode(AT, InsertPos);
2181 return QualType(AT, 0);
2182}
2183
Reid Kleckner8a365022013-06-24 17:51:48 +00002184QualType ASTContext::getDecayedType(QualType T) const {
2185 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2186
Reid Kleckner8a365022013-06-24 17:51:48 +00002187 QualType Decayed;
2188
2189 // C99 6.7.5.3p7:
2190 // A declaration of a parameter as "array of type" shall be
2191 // adjusted to "qualified pointer to type", where the type
2192 // qualifiers (if any) are those specified within the [ and ] of
2193 // the array type derivation.
2194 if (T->isArrayType())
2195 Decayed = getArrayDecayedType(T);
2196
2197 // C99 6.7.5.3p8:
2198 // A declaration of a parameter as "function returning type"
2199 // shall be adjusted to "pointer to function returning type", as
2200 // in 6.3.2.1.
2201 if (T->isFunctionType())
2202 Decayed = getPointerType(T);
2203
Reid Kleckner0503a872013-12-05 01:23:43 +00002204 llvm::FoldingSetNodeID ID;
2205 AdjustedType::Profile(ID, T, Decayed);
2206 void *InsertPos = 0;
2207 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2208 if (AT)
2209 return QualType(AT, 0);
2210
Reid Kleckner8a365022013-06-24 17:51:48 +00002211 QualType Canonical = getCanonicalType(Decayed);
2212
2213 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002214 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2215 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002216
Reid Kleckner0503a872013-12-05 01:23:43 +00002217 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2218 Types.push_back(AT);
2219 AdjustedTypes.InsertNode(AT, InsertPos);
2220 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002221}
2222
Mike Stump11289f42009-09-09 15:08:12 +00002223/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002224/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002225QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002226 assert(T->isFunctionType() && "block of function types only");
2227 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002228 // structure.
2229 llvm::FoldingSetNodeID ID;
2230 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002231
Steve Naroffec33ed92008-08-27 16:04:49 +00002232 void *InsertPos = 0;
2233 if (BlockPointerType *PT =
2234 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2235 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002236
2237 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002238 // type either so fill in the canonical type field.
2239 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002240 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002241 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002242
Steve Naroffec33ed92008-08-27 16:04:49 +00002243 // Get the new insert position for the node we care about.
2244 BlockPointerType *NewIP =
2245 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002246 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002247 }
John McCall90d1c2d2009-09-24 23:30:46 +00002248 BlockPointerType *New
2249 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002250 Types.push_back(New);
2251 BlockPointerTypes.InsertNode(New, InsertPos);
2252 return QualType(New, 0);
2253}
2254
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002255/// getLValueReferenceType - Return the uniqued reference to the type for an
2256/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002257QualType
2258ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002259 assert(getCanonicalType(T) != OverloadTy &&
2260 "Unresolved overloaded function type");
2261
Bill Wendling3708c182007-05-27 10:15:43 +00002262 // Unique pointers, to guarantee there is only one pointer of a particular
2263 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002264 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002265 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002266
2267 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002268 if (LValueReferenceType *RT =
2269 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002270 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002271
John McCallfc93cf92009-10-22 22:37:11 +00002272 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2273
Bill Wendling3708c182007-05-27 10:15:43 +00002274 // If the referencee type isn't canonical, this won't be a canonical type
2275 // either, so fill in the canonical type field.
2276 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002277 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2278 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2279 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002280
Bill Wendling3708c182007-05-27 10:15:43 +00002281 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002282 LValueReferenceType *NewIP =
2283 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002284 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002285 }
2286
John McCall90d1c2d2009-09-24 23:30:46 +00002287 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002288 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2289 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002290 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002291 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002292
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002293 return QualType(New, 0);
2294}
2295
2296/// getRValueReferenceType - Return the uniqued reference to the type for an
2297/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002298QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002299 // Unique pointers, to guarantee there is only one pointer of a particular
2300 // structure.
2301 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002302 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002303
2304 void *InsertPos = 0;
2305 if (RValueReferenceType *RT =
2306 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2307 return QualType(RT, 0);
2308
John McCallfc93cf92009-10-22 22:37:11 +00002309 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2310
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002311 // If the referencee type isn't canonical, this won't be a canonical type
2312 // either, so fill in the canonical type field.
2313 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002314 if (InnerRef || !T.isCanonical()) {
2315 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2316 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002317
2318 // Get the new insert position for the node we care about.
2319 RValueReferenceType *NewIP =
2320 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002321 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002322 }
2323
John McCall90d1c2d2009-09-24 23:30:46 +00002324 RValueReferenceType *New
2325 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002326 Types.push_back(New);
2327 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002328 return QualType(New, 0);
2329}
2330
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002331/// getMemberPointerType - Return the uniqued reference to the type for a
2332/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002333QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002334 // Unique pointers, to guarantee there is only one pointer of a particular
2335 // structure.
2336 llvm::FoldingSetNodeID ID;
2337 MemberPointerType::Profile(ID, T, Cls);
2338
2339 void *InsertPos = 0;
2340 if (MemberPointerType *PT =
2341 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2342 return QualType(PT, 0);
2343
2344 // If the pointee or class type isn't canonical, this won't be a canonical
2345 // type either, so fill in the canonical type field.
2346 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002347 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002348 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2349
2350 // Get the new insert position for the node we care about.
2351 MemberPointerType *NewIP =
2352 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002353 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002354 }
John McCall90d1c2d2009-09-24 23:30:46 +00002355 MemberPointerType *New
2356 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002357 Types.push_back(New);
2358 MemberPointerTypes.InsertNode(New, InsertPos);
2359 return QualType(New, 0);
2360}
2361
Mike Stump11289f42009-09-09 15:08:12 +00002362/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002363/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002364QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002365 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002366 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002367 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002368 assert((EltTy->isDependentType() ||
2369 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002370 "Constant array of VLAs is illegal!");
2371
Chris Lattnere2df3f92009-05-13 04:12:56 +00002372 // Convert the array size into a canonical width matching the pointer size for
2373 // the target.
2374 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002375 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002376 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002377
Chris Lattner23b7eb62007-06-15 23:05:46 +00002378 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002379 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002380
Chris Lattner36f8e652007-01-27 08:31:04 +00002381 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002382 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002383 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002384 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002385
John McCall33ddac02011-01-19 10:06:00 +00002386 // If the element type isn't canonical or has qualifiers, this won't
2387 // be a canonical type either, so fill in the canonical type field.
2388 QualType Canon;
2389 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2390 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002391 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002392 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002393 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002394
Chris Lattner36f8e652007-01-27 08:31:04 +00002395 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002396 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002397 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002398 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002399 }
Mike Stump11289f42009-09-09 15:08:12 +00002400
John McCall90d1c2d2009-09-24 23:30:46 +00002401 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002402 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002403 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002404 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002405 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002406}
2407
John McCall06549462011-01-18 08:40:38 +00002408/// getVariableArrayDecayedType - Turns the given type, which may be
2409/// variably-modified, into the corresponding type with all the known
2410/// sizes replaced with [*].
2411QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2412 // Vastly most common case.
2413 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002414
John McCall06549462011-01-18 08:40:38 +00002415 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002416
John McCall06549462011-01-18 08:40:38 +00002417 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002418 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002419 switch (ty->getTypeClass()) {
2420#define TYPE(Class, Base)
2421#define ABSTRACT_TYPE(Class, Base)
2422#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2423#include "clang/AST/TypeNodes.def"
2424 llvm_unreachable("didn't desugar past all non-canonical types?");
2425
2426 // These types should never be variably-modified.
2427 case Type::Builtin:
2428 case Type::Complex:
2429 case Type::Vector:
2430 case Type::ExtVector:
2431 case Type::DependentSizedExtVector:
2432 case Type::ObjCObject:
2433 case Type::ObjCInterface:
2434 case Type::ObjCObjectPointer:
2435 case Type::Record:
2436 case Type::Enum:
2437 case Type::UnresolvedUsing:
2438 case Type::TypeOfExpr:
2439 case Type::TypeOf:
2440 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002441 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002442 case Type::DependentName:
2443 case Type::InjectedClassName:
2444 case Type::TemplateSpecialization:
2445 case Type::DependentTemplateSpecialization:
2446 case Type::TemplateTypeParm:
2447 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002448 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002449 case Type::PackExpansion:
2450 llvm_unreachable("type should never be variably-modified");
2451
2452 // These types can be variably-modified but should never need to
2453 // further decay.
2454 case Type::FunctionNoProto:
2455 case Type::FunctionProto:
2456 case Type::BlockPointer:
2457 case Type::MemberPointer:
2458 return type;
2459
2460 // These types can be variably-modified. All these modifications
2461 // preserve structure except as noted by comments.
2462 // TODO: if we ever care about optimizing VLAs, there are no-op
2463 // optimizations available here.
2464 case Type::Pointer:
2465 result = getPointerType(getVariableArrayDecayedType(
2466 cast<PointerType>(ty)->getPointeeType()));
2467 break;
2468
2469 case Type::LValueReference: {
2470 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2471 result = getLValueReferenceType(
2472 getVariableArrayDecayedType(lv->getPointeeType()),
2473 lv->isSpelledAsLValue());
2474 break;
2475 }
2476
2477 case Type::RValueReference: {
2478 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2479 result = getRValueReferenceType(
2480 getVariableArrayDecayedType(lv->getPointeeType()));
2481 break;
2482 }
2483
Eli Friedman0dfb8892011-10-06 23:00:33 +00002484 case Type::Atomic: {
2485 const AtomicType *at = cast<AtomicType>(ty);
2486 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2487 break;
2488 }
2489
John McCall06549462011-01-18 08:40:38 +00002490 case Type::ConstantArray: {
2491 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2492 result = getConstantArrayType(
2493 getVariableArrayDecayedType(cat->getElementType()),
2494 cat->getSize(),
2495 cat->getSizeModifier(),
2496 cat->getIndexTypeCVRQualifiers());
2497 break;
2498 }
2499
2500 case Type::DependentSizedArray: {
2501 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2502 result = getDependentSizedArrayType(
2503 getVariableArrayDecayedType(dat->getElementType()),
2504 dat->getSizeExpr(),
2505 dat->getSizeModifier(),
2506 dat->getIndexTypeCVRQualifiers(),
2507 dat->getBracketsRange());
2508 break;
2509 }
2510
2511 // Turn incomplete types into [*] types.
2512 case Type::IncompleteArray: {
2513 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2514 result = getVariableArrayType(
2515 getVariableArrayDecayedType(iat->getElementType()),
2516 /*size*/ 0,
2517 ArrayType::Normal,
2518 iat->getIndexTypeCVRQualifiers(),
2519 SourceRange());
2520 break;
2521 }
2522
2523 // Turn VLA types into [*] types.
2524 case Type::VariableArray: {
2525 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2526 result = getVariableArrayType(
2527 getVariableArrayDecayedType(vat->getElementType()),
2528 /*size*/ 0,
2529 ArrayType::Star,
2530 vat->getIndexTypeCVRQualifiers(),
2531 vat->getBracketsRange());
2532 break;
2533 }
2534 }
2535
2536 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002537 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002538}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002539
Steve Naroffcadebd02007-08-30 18:14:25 +00002540/// getVariableArrayType - Returns a non-unique reference to the type for a
2541/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002542QualType ASTContext::getVariableArrayType(QualType EltTy,
2543 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002544 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002545 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002546 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002547 // Since we don't unique expressions, it isn't possible to unique VLA's
2548 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002549 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002550
John McCall33ddac02011-01-19 10:06:00 +00002551 // Be sure to pull qualifiers off the element type.
2552 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2553 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002554 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002555 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002556 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002557 }
2558
John McCall90d1c2d2009-09-24 23:30:46 +00002559 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002560 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002561
2562 VariableArrayTypes.push_back(New);
2563 Types.push_back(New);
2564 return QualType(New, 0);
2565}
2566
Douglas Gregor4619e432008-12-05 23:32:09 +00002567/// getDependentSizedArrayType - Returns a non-unique reference to
2568/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002569/// type.
John McCall33ddac02011-01-19 10:06:00 +00002570QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2571 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002572 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002573 unsigned elementTypeQuals,
2574 SourceRange brackets) const {
2575 assert((!numElements || numElements->isTypeDependent() ||
2576 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002577 "Size must be type- or value-dependent!");
2578
John McCall33ddac02011-01-19 10:06:00 +00002579 // Dependently-sized array types that do not have a specified number
2580 // of elements will have their sizes deduced from a dependent
2581 // initializer. We do no canonicalization here at all, which is okay
2582 // because they can't be used in most locations.
2583 if (!numElements) {
2584 DependentSizedArrayType *newType
2585 = new (*this, TypeAlignment)
2586 DependentSizedArrayType(*this, elementType, QualType(),
2587 numElements, ASM, elementTypeQuals,
2588 brackets);
2589 Types.push_back(newType);
2590 return QualType(newType, 0);
2591 }
2592
2593 // Otherwise, we actually build a new type every time, but we
2594 // also build a canonical type.
2595
2596 SplitQualType canonElementType = getCanonicalType(elementType).split();
2597
2598 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002599 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002600 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002601 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002602 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002603
John McCall33ddac02011-01-19 10:06:00 +00002604 // Look for an existing type with these properties.
2605 DependentSizedArrayType *canonTy =
2606 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002607
John McCall33ddac02011-01-19 10:06:00 +00002608 // If we don't have one, build one.
2609 if (!canonTy) {
2610 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002611 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002612 QualType(), numElements, ASM, elementTypeQuals,
2613 brackets);
2614 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2615 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002616 }
2617
John McCall33ddac02011-01-19 10:06:00 +00002618 // Apply qualifiers from the element type to the array.
2619 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002620 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002621
John McCall33ddac02011-01-19 10:06:00 +00002622 // If we didn't need extra canonicalization for the element type,
2623 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002624 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002625 return canon;
2626
2627 // Otherwise, we need to build a type which follows the spelling
2628 // of the element type.
2629 DependentSizedArrayType *sugaredType
2630 = new (*this, TypeAlignment)
2631 DependentSizedArrayType(*this, elementType, canon, numElements,
2632 ASM, elementTypeQuals, brackets);
2633 Types.push_back(sugaredType);
2634 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002635}
2636
John McCall33ddac02011-01-19 10:06:00 +00002637QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002638 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002639 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002640 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002641 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002642
John McCall33ddac02011-01-19 10:06:00 +00002643 void *insertPos = 0;
2644 if (IncompleteArrayType *iat =
2645 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2646 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002647
2648 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002649 // either, so fill in the canonical type field. We also have to pull
2650 // qualifiers off the element type.
2651 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002652
John McCall33ddac02011-01-19 10:06:00 +00002653 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2654 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002655 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002656 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002657 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002658
2659 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002660 IncompleteArrayType *existing =
2661 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2662 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002663 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002664
John McCall33ddac02011-01-19 10:06:00 +00002665 IncompleteArrayType *newType = new (*this, TypeAlignment)
2666 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002667
John McCall33ddac02011-01-19 10:06:00 +00002668 IncompleteArrayTypes.InsertNode(newType, insertPos);
2669 Types.push_back(newType);
2670 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002671}
2672
Steve Naroff91fcddb2007-07-18 18:00:27 +00002673/// getVectorType - Return the unique reference to a vector type of
2674/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002675QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002676 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002677 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002678
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002679 // Check if we've already instantiated a vector of this type.
2680 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002681 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002682
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002683 void *InsertPos = 0;
2684 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2685 return QualType(VTP, 0);
2686
2687 // If the element type isn't canonical, this won't be a canonical type either,
2688 // so fill in the canonical type field.
2689 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002690 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002691 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002692
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002693 // Get the new insert position for the node we care about.
2694 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002695 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002696 }
John McCall90d1c2d2009-09-24 23:30:46 +00002697 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002698 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002699 VectorTypes.InsertNode(New, InsertPos);
2700 Types.push_back(New);
2701 return QualType(New, 0);
2702}
2703
Nate Begemance4d7fc2008-04-18 23:10:10 +00002704/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002705/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002706QualType
2707ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002708 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002709
Steve Naroff91fcddb2007-07-18 18:00:27 +00002710 // Check if we've already instantiated a vector of this type.
2711 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002712 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002713 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002714 void *InsertPos = 0;
2715 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2716 return QualType(VTP, 0);
2717
2718 // If the element type isn't canonical, this won't be a canonical type either,
2719 // so fill in the canonical type field.
2720 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002721 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002722 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002723
Steve Naroff91fcddb2007-07-18 18:00:27 +00002724 // Get the new insert position for the node we care about.
2725 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002726 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002727 }
John McCall90d1c2d2009-09-24 23:30:46 +00002728 ExtVectorType *New = new (*this, TypeAlignment)
2729 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002730 VectorTypes.InsertNode(New, InsertPos);
2731 Types.push_back(New);
2732 return QualType(New, 0);
2733}
2734
Jay Foad39c79802011-01-12 09:06:06 +00002735QualType
2736ASTContext::getDependentSizedExtVectorType(QualType vecType,
2737 Expr *SizeExpr,
2738 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002739 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002740 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002741 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002742
Douglas Gregor352169a2009-07-31 03:54:25 +00002743 void *InsertPos = 0;
2744 DependentSizedExtVectorType *Canon
2745 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2746 DependentSizedExtVectorType *New;
2747 if (Canon) {
2748 // We already have a canonical version of this array type; use it as
2749 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002750 New = new (*this, TypeAlignment)
2751 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2752 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002753 } else {
2754 QualType CanonVecTy = getCanonicalType(vecType);
2755 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002756 New = new (*this, TypeAlignment)
2757 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2758 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002759
2760 DependentSizedExtVectorType *CanonCheck
2761 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2762 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2763 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002764 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2765 } else {
2766 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2767 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002768 New = new (*this, TypeAlignment)
2769 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002770 }
2771 }
Mike Stump11289f42009-09-09 15:08:12 +00002772
Douglas Gregor758a8692009-06-17 21:51:59 +00002773 Types.push_back(New);
2774 return QualType(New, 0);
2775}
2776
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002777/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002778///
Jay Foad39c79802011-01-12 09:06:06 +00002779QualType
2780ASTContext::getFunctionNoProtoType(QualType ResultTy,
2781 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002782 const CallingConv CallConv = Info.getCC();
2783
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002784 // Unique functions, to guarantee there is only one function of a particular
2785 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002786 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002787 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002788
Chris Lattner47955de2007-01-27 08:37:20 +00002789 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002790 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002791 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002792 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002793
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002794 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002795 if (!ResultTy.isCanonical()) {
2796 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002797
Chris Lattner47955de2007-01-27 08:37:20 +00002798 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002799 FunctionNoProtoType *NewIP =
2800 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002801 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002802 }
Mike Stump11289f42009-09-09 15:08:12 +00002803
Roman Divacky65b88cd2011-03-01 17:40:53 +00002804 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002805 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002806 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002807 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002808 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002809 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002810}
2811
Douglas Gregorcd780372013-01-17 23:36:45 +00002812/// \brief Determine whether \p T is canonical as the result type of a function.
2813static bool isCanonicalResultType(QualType T) {
2814 return T.isCanonical() &&
2815 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2816 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2817}
2818
Jay Foad39c79802011-01-12 09:06:06 +00002819QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002820ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002821 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002822 size_t NumArgs = ArgArray.size();
2823
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002824 // Unique functions, to guarantee there is only one function of a particular
2825 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002826 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002827 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2828 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002829
2830 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002831 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002832 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002833 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002834
2835 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002836 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002837 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002838 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002839 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002840 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002841 isCanonical = false;
2842
2843 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002844 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002845 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002846 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002847 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002848 CanonicalArgs.reserve(NumArgs);
2849 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002850 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002851
John McCalldb40c7f2010-12-14 08:05:40 +00002852 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002853 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002854 CanonicalEPI.ExceptionSpecType = EST_None;
2855 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002856
Douglas Gregorcd780372013-01-17 23:36:45 +00002857 // Result types do not have ARC lifetime qualifiers.
2858 QualType CanResultTy = getCanonicalType(ResultTy);
2859 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2860 Qualifiers Qs = CanResultTy.getQualifiers();
2861 Qs.removeObjCLifetime();
2862 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2863 }
2864
Jordan Rose5c382722013-03-08 21:51:21 +00002865 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002866
Chris Lattnerfd4de792007-01-27 01:15:32 +00002867 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002868 FunctionProtoType *NewIP =
2869 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002870 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002871 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002872
John McCall31168b02011-06-15 23:02:42 +00002873 // FunctionProtoType objects are allocated with extra bytes after
2874 // them for three variable size arrays at the end:
2875 // - parameter types
2876 // - exception types
2877 // - consumed-arguments flags
2878 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002879 // expression, or information used to resolve the exception
2880 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002881 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002882 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002883 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002884 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002885 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002886 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002887 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002888 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002889 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2890 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002891 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002892 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002893 Size += NumArgs * sizeof(bool);
2894
John McCalldb40c7f2010-12-14 08:05:40 +00002895 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002896 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002897 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002898 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002899 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002900 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002901}
Chris Lattneref51c202006-11-10 07:17:23 +00002902
John McCalle78aac42010-03-10 03:28:59 +00002903#ifndef NDEBUG
2904static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2905 if (!isa<CXXRecordDecl>(D)) return false;
2906 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2907 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2908 return true;
2909 if (RD->getDescribedClassTemplate() &&
2910 !isa<ClassTemplateSpecializationDecl>(RD))
2911 return true;
2912 return false;
2913}
2914#endif
2915
2916/// getInjectedClassNameType - Return the unique reference to the
2917/// injected class name type for the specified templated declaration.
2918QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002919 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002920 assert(NeedsInjectedClassNameType(Decl));
2921 if (Decl->TypeForDecl) {
2922 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002923 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002924 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2925 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2926 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2927 } else {
John McCall424cec92011-01-19 06:33:43 +00002928 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002929 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002930 Decl->TypeForDecl = newType;
2931 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002932 }
2933 return QualType(Decl->TypeForDecl, 0);
2934}
2935
Douglas Gregor83a586e2008-04-13 21:07:44 +00002936/// getTypeDeclType - Return the unique reference to the type for the
2937/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002938QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002939 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002940 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002941
Richard Smithdda56e42011-04-15 14:24:37 +00002942 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002943 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002944
John McCall96f0b5f2010-03-10 06:48:02 +00002945 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2946 "Template type parameter types are always available.");
2947
John McCall81e38502010-02-16 03:57:14 +00002948 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002949 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002950 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002951 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002952 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002953 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002954 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002955 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002956 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002957 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2958 Decl->TypeForDecl = newType;
2959 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002960 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002961 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002962
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002963 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002964}
2965
Chris Lattner32d920b2007-01-26 02:01:53 +00002966/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002967/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002968QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002969ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2970 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002971 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002972
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002973 if (Canonical.isNull())
2974 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002975 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002976 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002977 Decl->TypeForDecl = newType;
2978 Types.push_back(newType);
2979 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002980}
2981
Jay Foad39c79802011-01-12 09:06:06 +00002982QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002983 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2984
Douglas Gregorec9fd132012-01-14 16:38:05 +00002985 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002986 if (PrevDecl->TypeForDecl)
2987 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2988
John McCall424cec92011-01-19 06:33:43 +00002989 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2990 Decl->TypeForDecl = newType;
2991 Types.push_back(newType);
2992 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002993}
2994
Jay Foad39c79802011-01-12 09:06:06 +00002995QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002996 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2997
Douglas Gregorec9fd132012-01-14 16:38:05 +00002998 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002999 if (PrevDecl->TypeForDecl)
3000 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3001
John McCall424cec92011-01-19 06:33:43 +00003002 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3003 Decl->TypeForDecl = newType;
3004 Types.push_back(newType);
3005 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003006}
3007
John McCall81904512011-01-06 01:58:22 +00003008QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3009 QualType modifiedType,
3010 QualType equivalentType) {
3011 llvm::FoldingSetNodeID id;
3012 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3013
3014 void *insertPos = 0;
3015 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3016 if (type) return QualType(type, 0);
3017
3018 QualType canon = getCanonicalType(equivalentType);
3019 type = new (*this, TypeAlignment)
3020 AttributedType(canon, attrKind, modifiedType, equivalentType);
3021
3022 Types.push_back(type);
3023 AttributedTypes.InsertNode(type, insertPos);
3024
3025 return QualType(type, 0);
3026}
3027
3028
John McCallcebee162009-10-18 09:09:24 +00003029/// \brief Retrieve a substitution-result type.
3030QualType
3031ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003032 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003033 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003034 && "replacement types must always be canonical");
3035
3036 llvm::FoldingSetNodeID ID;
3037 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3038 void *InsertPos = 0;
3039 SubstTemplateTypeParmType *SubstParm
3040 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3041
3042 if (!SubstParm) {
3043 SubstParm = new (*this, TypeAlignment)
3044 SubstTemplateTypeParmType(Parm, Replacement);
3045 Types.push_back(SubstParm);
3046 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3047 }
3048
3049 return QualType(SubstParm, 0);
3050}
3051
Douglas Gregorada4b792011-01-14 02:55:32 +00003052/// \brief Retrieve a
3053QualType ASTContext::getSubstTemplateTypeParmPackType(
3054 const TemplateTypeParmType *Parm,
3055 const TemplateArgument &ArgPack) {
3056#ifndef NDEBUG
3057 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3058 PEnd = ArgPack.pack_end();
3059 P != PEnd; ++P) {
3060 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3061 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3062 }
3063#endif
3064
3065 llvm::FoldingSetNodeID ID;
3066 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3067 void *InsertPos = 0;
3068 if (SubstTemplateTypeParmPackType *SubstParm
3069 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3070 return QualType(SubstParm, 0);
3071
3072 QualType Canon;
3073 if (!Parm->isCanonicalUnqualified()) {
3074 Canon = getCanonicalType(QualType(Parm, 0));
3075 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3076 ArgPack);
3077 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3078 }
3079
3080 SubstTemplateTypeParmPackType *SubstParm
3081 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3082 ArgPack);
3083 Types.push_back(SubstParm);
3084 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3085 return QualType(SubstParm, 0);
3086}
3087
Douglas Gregoreff93e02009-02-05 23:33:38 +00003088/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003089/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003090/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003091QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003092 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003093 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003094 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003095 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003096 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003097 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003098 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3099
3100 if (TypeParm)
3101 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003102
Chandler Carruth08836322011-05-01 00:51:33 +00003103 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003104 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003105 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003106
3107 TemplateTypeParmType *TypeCheck
3108 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3109 assert(!TypeCheck && "Template type parameter canonical type broken");
3110 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003111 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003112 TypeParm = new (*this, TypeAlignment)
3113 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003114
3115 Types.push_back(TypeParm);
3116 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3117
3118 return QualType(TypeParm, 0);
3119}
3120
John McCalle78aac42010-03-10 03:28:59 +00003121TypeSourceInfo *
3122ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3123 SourceLocation NameLoc,
3124 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003125 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003126 assert(!Name.getAsDependentTemplateName() &&
3127 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003128 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003129
3130 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003131 TemplateSpecializationTypeLoc TL =
3132 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003133 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003134 TL.setTemplateNameLoc(NameLoc);
3135 TL.setLAngleLoc(Args.getLAngleLoc());
3136 TL.setRAngleLoc(Args.getRAngleLoc());
3137 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3138 TL.setArgLocInfo(i, Args[i].getLocInfo());
3139 return DI;
3140}
3141
Mike Stump11289f42009-09-09 15:08:12 +00003142QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003143ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003144 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003145 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003146 assert(!Template.getAsDependentTemplateName() &&
3147 "No dependent template names here!");
3148
John McCall6b51f282009-11-23 01:53:49 +00003149 unsigned NumArgs = Args.size();
3150
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003151 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003152 ArgVec.reserve(NumArgs);
3153 for (unsigned i = 0; i != NumArgs; ++i)
3154 ArgVec.push_back(Args[i].getArgument());
3155
John McCall2408e322010-04-27 00:57:59 +00003156 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003157 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003158}
3159
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003160#ifndef NDEBUG
3161static bool hasAnyPackExpansions(const TemplateArgument *Args,
3162 unsigned NumArgs) {
3163 for (unsigned I = 0; I != NumArgs; ++I)
3164 if (Args[I].isPackExpansion())
3165 return true;
3166
3167 return true;
3168}
3169#endif
3170
John McCall0ad16662009-10-29 08:12:44 +00003171QualType
3172ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003173 const TemplateArgument *Args,
3174 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003175 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003176 assert(!Template.getAsDependentTemplateName() &&
3177 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003178 // Look through qualified template names.
3179 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3180 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003181
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003182 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003183 Template.getAsTemplateDecl() &&
3184 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003185 QualType CanonType;
3186 if (!Underlying.isNull())
3187 CanonType = getCanonicalType(Underlying);
3188 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003189 // We can get here with an alias template when the specialization contains
3190 // a pack expansion that does not match up with a parameter pack.
3191 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3192 "Caller must compute aliased type");
3193 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003194 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3195 NumArgs);
3196 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003197
Douglas Gregora8e02e72009-07-28 23:00:59 +00003198 // Allocate the (non-canonical) template specialization type, but don't
3199 // try to unique it: these types typically have location information that
3200 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003201 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3202 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003203 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003204 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003205 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003206 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3207 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003208
Douglas Gregor8bf42052009-02-09 18:46:07 +00003209 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003210 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003211}
3212
Mike Stump11289f42009-09-09 15:08:12 +00003213QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003214ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3215 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003216 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003217 assert(!Template.getAsDependentTemplateName() &&
3218 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003219
Douglas Gregore29139c2011-03-03 17:04:51 +00003220 // Look through qualified template names.
3221 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3222 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003223
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003224 // Build the canonical template specialization type.
3225 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003226 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003227 CanonArgs.reserve(NumArgs);
3228 for (unsigned I = 0; I != NumArgs; ++I)
3229 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3230
3231 // Determine whether this canonical template specialization type already
3232 // exists.
3233 llvm::FoldingSetNodeID ID;
3234 TemplateSpecializationType::Profile(ID, CanonTemplate,
3235 CanonArgs.data(), NumArgs, *this);
3236
3237 void *InsertPos = 0;
3238 TemplateSpecializationType *Spec
3239 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3240
3241 if (!Spec) {
3242 // Allocate a new canonical template specialization type.
3243 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3244 sizeof(TemplateArgument) * NumArgs),
3245 TypeAlignment);
3246 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3247 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003248 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003249 Types.push_back(Spec);
3250 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3251 }
3252
3253 assert(Spec->isDependentType() &&
3254 "Non-dependent template-id type must have a canonical type");
3255 return QualType(Spec, 0);
3256}
3257
3258QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003259ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3260 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003261 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003262 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003263 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003264
3265 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003266 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003267 if (T)
3268 return QualType(T, 0);
3269
Douglas Gregorc42075a2010-02-04 18:10:26 +00003270 QualType Canon = NamedType;
3271 if (!Canon.isCanonical()) {
3272 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003273 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3274 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003275 (void)CheckT;
3276 }
3277
Abramo Bagnara6150c882010-05-11 21:36:43 +00003278 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003279 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003280 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003281 return QualType(T, 0);
3282}
3283
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003284QualType
Jay Foad39c79802011-01-12 09:06:06 +00003285ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003286 llvm::FoldingSetNodeID ID;
3287 ParenType::Profile(ID, InnerType);
3288
3289 void *InsertPos = 0;
3290 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3291 if (T)
3292 return QualType(T, 0);
3293
3294 QualType Canon = InnerType;
3295 if (!Canon.isCanonical()) {
3296 Canon = getCanonicalType(InnerType);
3297 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3298 assert(!CheckT && "Paren canonical type broken");
3299 (void)CheckT;
3300 }
3301
3302 T = new (*this) ParenType(InnerType, Canon);
3303 Types.push_back(T);
3304 ParenTypes.InsertNode(T, InsertPos);
3305 return QualType(T, 0);
3306}
3307
Douglas Gregor02085352010-03-31 20:19:30 +00003308QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3309 NestedNameSpecifier *NNS,
3310 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003311 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003312 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3313
3314 if (Canon.isNull()) {
3315 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003316 ElaboratedTypeKeyword CanonKeyword = Keyword;
3317 if (Keyword == ETK_None)
3318 CanonKeyword = ETK_Typename;
3319
3320 if (CanonNNS != NNS || CanonKeyword != Keyword)
3321 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003322 }
3323
3324 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003325 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003326
3327 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003328 DependentNameType *T
3329 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003330 if (T)
3331 return QualType(T, 0);
3332
Douglas Gregor02085352010-03-31 20:19:30 +00003333 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003334 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003335 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003336 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003337}
3338
Mike Stump11289f42009-09-09 15:08:12 +00003339QualType
John McCallc392f372010-06-11 00:33:02 +00003340ASTContext::getDependentTemplateSpecializationType(
3341 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003342 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003343 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003344 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003345 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003346 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003347 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3348 ArgCopy.push_back(Args[I].getArgument());
3349 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3350 ArgCopy.size(),
3351 ArgCopy.data());
3352}
3353
3354QualType
3355ASTContext::getDependentTemplateSpecializationType(
3356 ElaboratedTypeKeyword Keyword,
3357 NestedNameSpecifier *NNS,
3358 const IdentifierInfo *Name,
3359 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003360 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003361 assert((!NNS || NNS->isDependent()) &&
3362 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003363
Douglas Gregorc42075a2010-02-04 18:10:26 +00003364 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003365 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3366 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003367
3368 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003369 DependentTemplateSpecializationType *T
3370 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003371 if (T)
3372 return QualType(T, 0);
3373
John McCallc392f372010-06-11 00:33:02 +00003374 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003375
John McCallc392f372010-06-11 00:33:02 +00003376 ElaboratedTypeKeyword CanonKeyword = Keyword;
3377 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3378
3379 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003380 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003381 for (unsigned I = 0; I != NumArgs; ++I) {
3382 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3383 if (!CanonArgs[I].structurallyEquals(Args[I]))
3384 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003385 }
3386
John McCallc392f372010-06-11 00:33:02 +00003387 QualType Canon;
3388 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3389 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3390 Name, NumArgs,
3391 CanonArgs.data());
3392
3393 // Find the insert position again.
3394 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3395 }
3396
3397 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3398 sizeof(TemplateArgument) * NumArgs),
3399 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003400 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003401 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003402 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003403 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003404 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003405}
3406
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003407QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003408 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003409 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003410 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003411
3412 assert(Pattern->containsUnexpandedParameterPack() &&
3413 "Pack expansions must expand one or more parameter packs");
3414 void *InsertPos = 0;
3415 PackExpansionType *T
3416 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3417 if (T)
3418 return QualType(T, 0);
3419
3420 QualType Canon;
3421 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003422 Canon = getCanonicalType(Pattern);
3423 // The canonical type might not contain an unexpanded parameter pack, if it
3424 // contains an alias template specialization which ignores one of its
3425 // parameters.
3426 if (Canon->containsUnexpandedParameterPack()) {
3427 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003428
Richard Smith68eea502012-07-16 00:20:35 +00003429 // Find the insert position again, in case we inserted an element into
3430 // PackExpansionTypes and invalidated our insert position.
3431 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3432 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003433 }
3434
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003435 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003436 Types.push_back(T);
3437 PackExpansionTypes.InsertNode(T, InsertPos);
3438 return QualType(T, 0);
3439}
3440
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003441/// CmpProtocolNames - Comparison predicate for sorting protocols
3442/// alphabetically.
3443static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3444 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003445 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003446}
3447
John McCall8b07ec22010-05-15 11:32:37 +00003448static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003449 unsigned NumProtocols) {
3450 if (NumProtocols == 0) return true;
3451
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003452 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3453 return false;
3454
John McCallfc93cf92009-10-22 22:37:11 +00003455 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003456 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3457 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003458 return false;
3459 return true;
3460}
3461
3462static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003463 unsigned &NumProtocols) {
3464 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003465
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003466 // Sort protocols, keyed by name.
3467 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3468
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003469 // Canonicalize.
3470 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3471 Protocols[I] = Protocols[I]->getCanonicalDecl();
3472
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003473 // Remove duplicates.
3474 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3475 NumProtocols = ProtocolsEnd-Protocols;
3476}
3477
John McCall8b07ec22010-05-15 11:32:37 +00003478QualType ASTContext::getObjCObjectType(QualType BaseType,
3479 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003480 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003481 // If the base type is an interface and there aren't any protocols
3482 // to add, then the interface type will do just fine.
3483 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3484 return BaseType;
3485
3486 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003487 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003488 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003489 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003490 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3491 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003492
John McCall8b07ec22010-05-15 11:32:37 +00003493 // Build the canonical type, which has the canonical base type and
3494 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003495 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003496 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3497 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3498 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003499 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003500 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003501 unsigned UniqueCount = NumProtocols;
3502
John McCallfc93cf92009-10-22 22:37:11 +00003503 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003504 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3505 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003506 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003507 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3508 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003509 }
3510
3511 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003512 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3513 }
3514
3515 unsigned Size = sizeof(ObjCObjectTypeImpl);
3516 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3517 void *Mem = Allocate(Size, TypeAlignment);
3518 ObjCObjectTypeImpl *T =
3519 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3520
3521 Types.push_back(T);
3522 ObjCObjectTypes.InsertNode(T, InsertPos);
3523 return QualType(T, 0);
3524}
3525
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003526/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3527/// protocol list adopt all protocols in QT's qualified-id protocol
3528/// list.
3529bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3530 ObjCInterfaceDecl *IC) {
3531 if (!QT->isObjCQualifiedIdType())
3532 return false;
3533
3534 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3535 // If both the right and left sides have qualifiers.
3536 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3537 E = OPT->qual_end(); I != E; ++I) {
3538 ObjCProtocolDecl *Proto = *I;
3539 if (!IC->ClassImplementsProtocol(Proto, false))
3540 return false;
3541 }
3542 return true;
3543 }
3544 return false;
3545}
3546
3547/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3548/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3549/// of protocols.
3550bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3551 ObjCInterfaceDecl *IDecl) {
3552 if (!QT->isObjCQualifiedIdType())
3553 return false;
3554 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3555 if (!OPT)
3556 return false;
3557 if (!IDecl->hasDefinition())
3558 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003559 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3560 CollectInheritedProtocols(IDecl, InheritedProtocols);
3561 if (InheritedProtocols.empty())
3562 return false;
3563
3564 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3565 InheritedProtocols.begin(),
3566 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003567 // If both the right and left sides have qualifiers.
3568 bool Adopts = false;
3569 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3570 E = OPT->qual_end(); I != E; ++I) {
3571 ObjCProtocolDecl *Proto = *I;
3572 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3573 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3574 break;
3575 }
3576 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003577 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003578 }
3579 return true;
3580}
3581
John McCall8b07ec22010-05-15 11:32:37 +00003582/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3583/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003584QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003585 llvm::FoldingSetNodeID ID;
3586 ObjCObjectPointerType::Profile(ID, ObjectT);
3587
3588 void *InsertPos = 0;
3589 if (ObjCObjectPointerType *QT =
3590 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3591 return QualType(QT, 0);
3592
3593 // Find the canonical object type.
3594 QualType Canonical;
3595 if (!ObjectT.isCanonical()) {
3596 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3597
3598 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003599 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3600 }
3601
Douglas Gregorf85bee62010-02-08 22:59:26 +00003602 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003603 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3604 ObjCObjectPointerType *QType =
3605 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003606
Steve Narofffb4330f2009-06-17 22:40:22 +00003607 Types.push_back(QType);
3608 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003609 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003610}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003611
Douglas Gregor1c283312010-08-11 12:19:30 +00003612/// getObjCInterfaceType - Return the unique reference to the type for the
3613/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003614QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3615 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003616 if (Decl->TypeForDecl)
3617 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003618
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003619 if (PrevDecl) {
3620 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3621 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3622 return QualType(PrevDecl->TypeForDecl, 0);
3623 }
3624
Douglas Gregor7671e532011-12-16 16:34:57 +00003625 // Prefer the definition, if there is one.
3626 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3627 Decl = Def;
3628
Douglas Gregor1c283312010-08-11 12:19:30 +00003629 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3630 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3631 Decl->TypeForDecl = T;
3632 Types.push_back(T);
3633 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003634}
3635
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003636/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3637/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003638/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003639/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003640/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003641QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003642 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003643 if (tofExpr->isTypeDependent()) {
3644 llvm::FoldingSetNodeID ID;
3645 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003646
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003647 void *InsertPos = 0;
3648 DependentTypeOfExprType *Canon
3649 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3650 if (Canon) {
3651 // We already have a "canonical" version of an identical, dependent
3652 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003653 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003654 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003655 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003656 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003657 Canon
3658 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003659 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3660 toe = Canon;
3661 }
3662 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003663 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003664 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003665 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003666 Types.push_back(toe);
3667 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003668}
3669
Steve Naroffa773cd52007-08-01 18:02:17 +00003670/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3671/// TypeOfType AST's. The only motivation to unique these nodes would be
3672/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003673/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003674/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003675QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003676 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003677 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003678 Types.push_back(tot);
3679 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003680}
3681
Anders Carlssonad6bd352009-06-24 21:24:56 +00003682
Anders Carlsson81df7b82009-06-24 19:06:50 +00003683/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3684/// DecltypeType AST's. The only motivation to unique these nodes would be
3685/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003686/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003687/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003688QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003689 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003690
3691 // C++0x [temp.type]p2:
3692 // If an expression e involves a template parameter, decltype(e) denotes a
3693 // unique dependent type. Two such decltype-specifiers refer to the same
3694 // type only if their expressions are equivalent (14.5.6.1).
3695 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003696 llvm::FoldingSetNodeID ID;
3697 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003698
Douglas Gregora21f6c32009-07-30 23:36:40 +00003699 void *InsertPos = 0;
3700 DependentDecltypeType *Canon
3701 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3702 if (Canon) {
3703 // We already have a "canonical" version of an equivalent, dependent
3704 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003705 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003706 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003707 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003708 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003709 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003710 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3711 dt = Canon;
3712 }
3713 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003714 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3715 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003716 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003717 Types.push_back(dt);
3718 return QualType(dt, 0);
3719}
3720
Alexis Hunte852b102011-05-24 22:41:36 +00003721/// getUnaryTransformationType - We don't unique these, since the memory
3722/// savings are minimal and these are rare.
3723QualType ASTContext::getUnaryTransformType(QualType BaseType,
3724 QualType UnderlyingType,
3725 UnaryTransformType::UTTKind Kind)
3726 const {
3727 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003728 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3729 Kind,
3730 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003731 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003732 Types.push_back(Ty);
3733 return QualType(Ty, 0);
3734}
3735
Richard Smith2a7d4812013-05-04 07:00:32 +00003736/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3737/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3738/// canonical deduced-but-dependent 'auto' type.
3739QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003740 bool IsDependent) const {
3741 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003742 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003743
Richard Smith2a7d4812013-05-04 07:00:32 +00003744 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003745 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003746 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003747 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003748 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3749 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003750
Richard Smith74aeef52013-04-26 16:15:35 +00003751 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003752 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003753 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003754 Types.push_back(AT);
3755 if (InsertPos)
3756 AutoTypes.InsertNode(AT, InsertPos);
3757 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003758}
3759
Eli Friedman0dfb8892011-10-06 23:00:33 +00003760/// getAtomicType - Return the uniqued reference to the atomic type for
3761/// the given value type.
3762QualType ASTContext::getAtomicType(QualType T) const {
3763 // Unique pointers, to guarantee there is only one pointer of a particular
3764 // structure.
3765 llvm::FoldingSetNodeID ID;
3766 AtomicType::Profile(ID, T);
3767
3768 void *InsertPos = 0;
3769 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3770 return QualType(AT, 0);
3771
3772 // If the atomic value type isn't canonical, this won't be a canonical type
3773 // either, so fill in the canonical type field.
3774 QualType Canonical;
3775 if (!T.isCanonical()) {
3776 Canonical = getAtomicType(getCanonicalType(T));
3777
3778 // Get the new insert position for the node we care about.
3779 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3780 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3781 }
3782 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3783 Types.push_back(New);
3784 AtomicTypes.InsertNode(New, InsertPos);
3785 return QualType(New, 0);
3786}
3787
Richard Smith02e85f32011-04-14 22:09:26 +00003788/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3789QualType ASTContext::getAutoDeductType() const {
3790 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003791 AutoDeductTy = QualType(
3792 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003793 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003794 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003795 return AutoDeductTy;
3796}
3797
3798/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3799QualType ASTContext::getAutoRRefDeductType() const {
3800 if (AutoRRefDeductTy.isNull())
3801 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3802 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3803 return AutoRRefDeductTy;
3804}
3805
Chris Lattnerfb072462007-01-23 05:45:31 +00003806/// getTagDeclType - Return the unique reference to the type for the
3807/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003808QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003809 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003810 // FIXME: What is the design on getTagDeclType when it requires casting
3811 // away const? mutable?
3812 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003813}
3814
Mike Stump11289f42009-09-09 15:08:12 +00003815/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3816/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3817/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003818CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003819 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003820}
Chris Lattnerfb072462007-01-23 05:45:31 +00003821
Hans Wennborg27541db2011-10-27 08:29:09 +00003822/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3823CanQualType ASTContext::getIntMaxType() const {
3824 return getFromTargetType(Target->getIntMaxType());
3825}
3826
3827/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3828CanQualType ASTContext::getUIntMaxType() const {
3829 return getFromTargetType(Target->getUIntMaxType());
3830}
3831
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003832/// getSignedWCharType - Return the type of "signed wchar_t".
3833/// Used when in C++, as a GCC extension.
3834QualType ASTContext::getSignedWCharType() const {
3835 // FIXME: derive from "Target" ?
3836 return WCharTy;
3837}
3838
3839/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3840/// Used when in C++, as a GCC extension.
3841QualType ASTContext::getUnsignedWCharType() const {
3842 // FIXME: derive from "Target" ?
3843 return UnsignedIntTy;
3844}
3845
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003846QualType ASTContext::getIntPtrType() const {
3847 return getFromTargetType(Target->getIntPtrType());
3848}
3849
3850QualType ASTContext::getUIntPtrType() const {
3851 return getCorrespondingUnsignedType(getIntPtrType());
3852}
3853
Hans Wennborg27541db2011-10-27 08:29:09 +00003854/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003855/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3856QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003857 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003858}
3859
Eli Friedman4e91899e2012-11-27 02:58:24 +00003860/// \brief Return the unique type for "pid_t" defined in
3861/// <sys/types.h>. We need this to compute the correct type for vfork().
3862QualType ASTContext::getProcessIDType() const {
3863 return getFromTargetType(Target->getProcessIDType());
3864}
3865
Chris Lattnera21ad802008-04-02 05:18:44 +00003866//===----------------------------------------------------------------------===//
3867// Type Operators
3868//===----------------------------------------------------------------------===//
3869
Jay Foad39c79802011-01-12 09:06:06 +00003870CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003871 // Push qualifiers into arrays, and then discard any remaining
3872 // qualifiers.
3873 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003874 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003875 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003876 QualType Result;
3877 if (isa<ArrayType>(Ty)) {
3878 Result = getArrayDecayedType(QualType(Ty,0));
3879 } else if (isa<FunctionType>(Ty)) {
3880 Result = getPointerType(QualType(Ty, 0));
3881 } else {
3882 Result = QualType(Ty, 0);
3883 }
3884
3885 return CanQualType::CreateUnsafe(Result);
3886}
3887
John McCall6c9dd522011-01-18 07:41:22 +00003888QualType ASTContext::getUnqualifiedArrayType(QualType type,
3889 Qualifiers &quals) {
3890 SplitQualType splitType = type.getSplitUnqualifiedType();
3891
3892 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3893 // the unqualified desugared type and then drops it on the floor.
3894 // We then have to strip that sugar back off with
3895 // getUnqualifiedDesugaredType(), which is silly.
3896 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003897 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003898
3899 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003900 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003901 quals = splitType.Quals;
3902 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003903 }
3904
John McCall6c9dd522011-01-18 07:41:22 +00003905 // Otherwise, recurse on the array's element type.
3906 QualType elementType = AT->getElementType();
3907 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3908
3909 // If that didn't change the element type, AT has no qualifiers, so we
3910 // can just use the results in splitType.
3911 if (elementType == unqualElementType) {
3912 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003913 quals = splitType.Quals;
3914 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003915 }
3916
3917 // Otherwise, add in the qualifiers from the outermost type, then
3918 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003919 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003920
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003921 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003922 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003923 CAT->getSizeModifier(), 0);
3924 }
3925
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003926 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003927 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003928 }
3929
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003930 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003931 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003932 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003933 VAT->getSizeModifier(),
3934 VAT->getIndexTypeCVRQualifiers(),
3935 VAT->getBracketsRange());
3936 }
3937
3938 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003939 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003940 DSAT->getSizeModifier(), 0,
3941 SourceRange());
3942}
3943
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003944/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3945/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3946/// they point to and return true. If T1 and T2 aren't pointer types
3947/// or pointer-to-member types, or if they are not similar at this
3948/// level, returns false and leaves T1 and T2 unchanged. Top-level
3949/// qualifiers on T1 and T2 are ignored. This function will typically
3950/// be called in a loop that successively "unwraps" pointer and
3951/// pointer-to-member types to compare them at each level.
3952bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3953 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3954 *T2PtrType = T2->getAs<PointerType>();
3955 if (T1PtrType && T2PtrType) {
3956 T1 = T1PtrType->getPointeeType();
3957 T2 = T2PtrType->getPointeeType();
3958 return true;
3959 }
3960
3961 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3962 *T2MPType = T2->getAs<MemberPointerType>();
3963 if (T1MPType && T2MPType &&
3964 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3965 QualType(T2MPType->getClass(), 0))) {
3966 T1 = T1MPType->getPointeeType();
3967 T2 = T2MPType->getPointeeType();
3968 return true;
3969 }
3970
David Blaikiebbafb8a2012-03-11 07:00:24 +00003971 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003972 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3973 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3974 if (T1OPType && T2OPType) {
3975 T1 = T1OPType->getPointeeType();
3976 T2 = T2OPType->getPointeeType();
3977 return true;
3978 }
3979 }
3980
3981 // FIXME: Block pointers, too?
3982
3983 return false;
3984}
3985
Jay Foad39c79802011-01-12 09:06:06 +00003986DeclarationNameInfo
3987ASTContext::getNameForTemplate(TemplateName Name,
3988 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003989 switch (Name.getKind()) {
3990 case TemplateName::QualifiedTemplate:
3991 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003992 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003993 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3994 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003995
John McCalld9dfe3a2011-06-30 08:33:18 +00003996 case TemplateName::OverloadedTemplate: {
3997 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3998 // DNInfo work in progress: CHECKME: what about DNLoc?
3999 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4000 }
4001
4002 case TemplateName::DependentTemplate: {
4003 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004004 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004005 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004006 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4007 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004008 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004009 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4010 // DNInfo work in progress: FIXME: source locations?
4011 DeclarationNameLoc DNLoc;
4012 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4013 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4014 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004015 }
4016 }
4017
John McCalld9dfe3a2011-06-30 08:33:18 +00004018 case TemplateName::SubstTemplateTemplateParm: {
4019 SubstTemplateTemplateParmStorage *subst
4020 = Name.getAsSubstTemplateTemplateParm();
4021 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4022 NameLoc);
4023 }
4024
4025 case TemplateName::SubstTemplateTemplateParmPack: {
4026 SubstTemplateTemplateParmPackStorage *subst
4027 = Name.getAsSubstTemplateTemplateParmPack();
4028 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4029 NameLoc);
4030 }
4031 }
4032
4033 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004034}
4035
Jay Foad39c79802011-01-12 09:06:06 +00004036TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004037 switch (Name.getKind()) {
4038 case TemplateName::QualifiedTemplate:
4039 case TemplateName::Template: {
4040 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004041 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004042 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004043 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4044
4045 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004046 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004047 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004048
John McCalld9dfe3a2011-06-30 08:33:18 +00004049 case TemplateName::OverloadedTemplate:
4050 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004051
John McCalld9dfe3a2011-06-30 08:33:18 +00004052 case TemplateName::DependentTemplate: {
4053 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4054 assert(DTN && "Non-dependent template names must refer to template decls.");
4055 return DTN->CanonicalTemplateName;
4056 }
4057
4058 case TemplateName::SubstTemplateTemplateParm: {
4059 SubstTemplateTemplateParmStorage *subst
4060 = Name.getAsSubstTemplateTemplateParm();
4061 return getCanonicalTemplateName(subst->getReplacement());
4062 }
4063
4064 case TemplateName::SubstTemplateTemplateParmPack: {
4065 SubstTemplateTemplateParmPackStorage *subst
4066 = Name.getAsSubstTemplateTemplateParmPack();
4067 TemplateTemplateParmDecl *canonParameter
4068 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4069 TemplateArgument canonArgPack
4070 = getCanonicalTemplateArgument(subst->getArgumentPack());
4071 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4072 }
4073 }
4074
4075 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004076}
4077
Douglas Gregoradee3e32009-11-11 23:06:43 +00004078bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4079 X = getCanonicalTemplateName(X);
4080 Y = getCanonicalTemplateName(Y);
4081 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4082}
4083
Mike Stump11289f42009-09-09 15:08:12 +00004084TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004085ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004086 switch (Arg.getKind()) {
4087 case TemplateArgument::Null:
4088 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004089
Douglas Gregora8e02e72009-07-28 23:00:59 +00004090 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004091 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004092
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004093 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004094 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4095 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004096 }
Mike Stump11289f42009-09-09 15:08:12 +00004097
Eli Friedmanb826a002012-09-26 02:36:12 +00004098 case TemplateArgument::NullPtr:
4099 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4100 /*isNullPtr*/true);
4101
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004102 case TemplateArgument::Template:
4103 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004104
4105 case TemplateArgument::TemplateExpansion:
4106 return TemplateArgument(getCanonicalTemplateName(
4107 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004108 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004109
Douglas Gregora8e02e72009-07-28 23:00:59 +00004110 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004111 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004112
Douglas Gregora8e02e72009-07-28 23:00:59 +00004113 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004114 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004115
Douglas Gregora8e02e72009-07-28 23:00:59 +00004116 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004117 if (Arg.pack_size() == 0)
4118 return Arg;
4119
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004120 TemplateArgument *CanonArgs
4121 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004122 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004123 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004124 AEnd = Arg.pack_end();
4125 A != AEnd; (void)++A, ++Idx)
4126 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004127
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004128 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004129 }
4130 }
4131
4132 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004133 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004134}
4135
Douglas Gregor333489b2009-03-27 23:10:48 +00004136NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004137ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004138 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004139 return 0;
4140
4141 switch (NNS->getKind()) {
4142 case NestedNameSpecifier::Identifier:
4143 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004144 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004145 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4146 NNS->getAsIdentifier());
4147
4148 case NestedNameSpecifier::Namespace:
4149 // A namespace is canonical; build a nested-name-specifier with
4150 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004151 return NestedNameSpecifier::Create(*this, 0,
4152 NNS->getAsNamespace()->getOriginalNamespace());
4153
4154 case NestedNameSpecifier::NamespaceAlias:
4155 // A namespace is canonical; build a nested-name-specifier with
4156 // this namespace and no prefix.
4157 return NestedNameSpecifier::Create(*this, 0,
4158 NNS->getAsNamespaceAlias()->getNamespace()
4159 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004160
4161 case NestedNameSpecifier::TypeSpec:
4162 case NestedNameSpecifier::TypeSpecWithTemplate: {
4163 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004164
4165 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4166 // break it apart into its prefix and identifier, then reconsititute those
4167 // as the canonical nested-name-specifier. This is required to canonicalize
4168 // a dependent nested-name-specifier involving typedefs of dependent-name
4169 // types, e.g.,
4170 // typedef typename T::type T1;
4171 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004172 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4173 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004174 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004175
Eli Friedman5358a0a2012-03-03 04:09:56 +00004176 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4177 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4178 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004179 return NestedNameSpecifier::Create(*this, 0, false,
4180 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004181 }
4182
4183 case NestedNameSpecifier::Global:
4184 // The global specifier is canonical and unique.
4185 return NNS;
4186 }
4187
David Blaikie8a40f702012-01-17 06:56:22 +00004188 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004189}
4190
Chris Lattner7adf0762008-08-04 07:31:14 +00004191
Jay Foad39c79802011-01-12 09:06:06 +00004192const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004193 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004194 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004195 // Handle the common positive case fast.
4196 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4197 return AT;
4198 }
Mike Stump11289f42009-09-09 15:08:12 +00004199
John McCall8ccfcb52009-09-24 19:53:00 +00004200 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004201 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004202 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004203
John McCall8ccfcb52009-09-24 19:53:00 +00004204 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004205 // implements C99 6.7.3p8: "If the specification of an array type includes
4206 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004207
Chris Lattner7adf0762008-08-04 07:31:14 +00004208 // If we get here, we either have type qualifiers on the type, or we have
4209 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004210 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004211
John McCall33ddac02011-01-19 10:06:00 +00004212 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004213 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004214
Chris Lattner7adf0762008-08-04 07:31:14 +00004215 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004216 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004217 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004218 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004219
Chris Lattner7adf0762008-08-04 07:31:14 +00004220 // Otherwise, we have an array and we have qualifiers on it. Push the
4221 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004222 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004223
Chris Lattner7adf0762008-08-04 07:31:14 +00004224 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4225 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4226 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004227 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004228 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4229 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4230 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004231 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004232
Mike Stump11289f42009-09-09 15:08:12 +00004233 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004234 = dyn_cast<DependentSizedArrayType>(ATy))
4235 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004236 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004237 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004238 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004239 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004240 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004241
Chris Lattner7adf0762008-08-04 07:31:14 +00004242 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004243 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004244 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004245 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004246 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004247 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004248}
4249
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004250QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004251 if (T->isArrayType() || T->isFunctionType())
4252 return getDecayedType(T);
4253 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004254}
4255
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004256QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004257 T = getVariableArrayDecayedType(T);
4258 T = getAdjustedParameterType(T);
4259 return T.getUnqualifiedType();
4260}
4261
Chris Lattnera21ad802008-04-02 05:18:44 +00004262/// getArrayDecayedType - Return the properly qualified result of decaying the
4263/// specified array type to a pointer. This operation is non-trivial when
4264/// handling typedefs etc. The canonical type of "T" must be an array type,
4265/// this returns a pointer to a properly qualified element of the array.
4266///
4267/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004268QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004269 // Get the element type with 'getAsArrayType' so that we don't lose any
4270 // typedefs in the element type of the array. This also handles propagation
4271 // of type qualifiers from the array type into the element type if present
4272 // (C99 6.7.3p8).
4273 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4274 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004275
Chris Lattner7adf0762008-08-04 07:31:14 +00004276 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004277
4278 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004279 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004280}
4281
John McCall33ddac02011-01-19 10:06:00 +00004282QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4283 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004284}
4285
John McCall33ddac02011-01-19 10:06:00 +00004286QualType ASTContext::getBaseElementType(QualType type) const {
4287 Qualifiers qs;
4288 while (true) {
4289 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004290 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004291 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004292
John McCall33ddac02011-01-19 10:06:00 +00004293 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004294 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004295 }
Mike Stump11289f42009-09-09 15:08:12 +00004296
John McCall33ddac02011-01-19 10:06:00 +00004297 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004298}
4299
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004300/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004301uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004302ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4303 uint64_t ElementCount = 1;
4304 do {
4305 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004306 CA = dyn_cast_or_null<ConstantArrayType>(
4307 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004308 } while (CA);
4309 return ElementCount;
4310}
4311
Steve Naroff0af91202007-04-27 21:51:21 +00004312/// getFloatingRank - Return a relative rank for floating point types.
4313/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004314static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004315 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004316 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004317
John McCall9dd450b2009-09-21 23:43:11 +00004318 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4319 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004320 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004321 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004322 case BuiltinType::Float: return FloatRank;
4323 case BuiltinType::Double: return DoubleRank;
4324 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004325 }
4326}
4327
Mike Stump11289f42009-09-09 15:08:12 +00004328/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4329/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004330/// 'typeDomain' is a real floating point or complex type.
4331/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004332QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4333 QualType Domain) const {
4334 FloatingRank EltRank = getFloatingRank(Size);
4335 if (Domain->isComplexType()) {
4336 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004337 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004338 case FloatRank: return FloatComplexTy;
4339 case DoubleRank: return DoubleComplexTy;
4340 case LongDoubleRank: return LongDoubleComplexTy;
4341 }
Steve Naroff0af91202007-04-27 21:51:21 +00004342 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004343
4344 assert(Domain->isRealFloatingType() && "Unknown domain!");
4345 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004346 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004347 case FloatRank: return FloatTy;
4348 case DoubleRank: return DoubleTy;
4349 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004350 }
David Blaikief47fa302012-01-17 02:30:50 +00004351 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004352}
4353
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004354/// getFloatingTypeOrder - Compare the rank of the two specified floating
4355/// point types, ignoring the domain of the type (i.e. 'double' ==
4356/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004357/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004358int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004359 FloatingRank LHSR = getFloatingRank(LHS);
4360 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004361
Chris Lattnerb90739d2008-04-06 23:38:49 +00004362 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004363 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004364 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004365 return 1;
4366 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004367}
4368
Chris Lattner76a00cf2008-04-06 22:59:24 +00004369/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4370/// routine will assert if passed a built-in type that isn't an integer or enum,
4371/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004372unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004373 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004374
Chris Lattner76a00cf2008-04-06 22:59:24 +00004375 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004376 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004377 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004378 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004379 case BuiltinType::Char_S:
4380 case BuiltinType::Char_U:
4381 case BuiltinType::SChar:
4382 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004383 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004384 case BuiltinType::Short:
4385 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004386 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004387 case BuiltinType::Int:
4388 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004389 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004390 case BuiltinType::Long:
4391 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004392 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004393 case BuiltinType::LongLong:
4394 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004395 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004396 case BuiltinType::Int128:
4397 case BuiltinType::UInt128:
4398 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004399 }
4400}
4401
Eli Friedman629ffb92009-08-20 04:21:42 +00004402/// \brief Whether this is a promotable bitfield reference according
4403/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4404///
4405/// \returns the type this bit-field will promote to, or NULL if no
4406/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004407QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004408 if (E->isTypeDependent() || E->isValueDependent())
4409 return QualType();
4410
John McCalld25db7e2013-05-06 21:39:12 +00004411 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004412 if (!Field)
4413 return QualType();
4414
4415 QualType FT = Field->getType();
4416
Richard Smithcaf33902011-10-10 18:28:20 +00004417 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004418 uint64_t IntSize = getTypeSize(IntTy);
4419 // GCC extension compatibility: if the bit-field size is less than or equal
4420 // to the size of int, it gets promoted no matter what its type is.
4421 // For instance, unsigned long bf : 4 gets promoted to signed int.
4422 if (BitWidth < IntSize)
4423 return IntTy;
4424
4425 if (BitWidth == IntSize)
4426 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4427
4428 // Types bigger than int are not subject to promotions, and therefore act
4429 // like the base type.
4430 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4431 // is ridiculous.
4432 return QualType();
4433}
4434
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004435/// getPromotedIntegerType - Returns the type that Promotable will
4436/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4437/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004438QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004439 assert(!Promotable.isNull());
4440 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004441 if (const EnumType *ET = Promotable->getAs<EnumType>())
4442 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004443
4444 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4445 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4446 // (3.9.1) can be converted to a prvalue of the first of the following
4447 // types that can represent all the values of its underlying type:
4448 // int, unsigned int, long int, unsigned long int, long long int, or
4449 // unsigned long long int [...]
4450 // FIXME: Is there some better way to compute this?
4451 if (BT->getKind() == BuiltinType::WChar_S ||
4452 BT->getKind() == BuiltinType::WChar_U ||
4453 BT->getKind() == BuiltinType::Char16 ||
4454 BT->getKind() == BuiltinType::Char32) {
4455 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4456 uint64_t FromSize = getTypeSize(BT);
4457 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4458 LongLongTy, UnsignedLongLongTy };
4459 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4460 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4461 if (FromSize < ToSize ||
4462 (FromSize == ToSize &&
4463 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4464 return PromoteTypes[Idx];
4465 }
4466 llvm_unreachable("char type should fit into long long");
4467 }
4468 }
4469
4470 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004471 if (Promotable->isSignedIntegerType())
4472 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004473 uint64_t PromotableSize = getIntWidth(Promotable);
4474 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004475 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4476 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4477}
4478
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004479/// \brief Recurses in pointer/array types until it finds an objc retainable
4480/// type and returns its ownership.
4481Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4482 while (!T.isNull()) {
4483 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4484 return T.getObjCLifetime();
4485 if (T->isArrayType())
4486 T = getBaseElementType(T);
4487 else if (const PointerType *PT = T->getAs<PointerType>())
4488 T = PT->getPointeeType();
4489 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004490 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004491 else
4492 break;
4493 }
4494
4495 return Qualifiers::OCL_None;
4496}
4497
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004498static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4499 // Incomplete enum types are not treated as integer types.
4500 // FIXME: In C++, enum types are never integer types.
4501 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4502 return ET->getDecl()->getIntegerType().getTypePtr();
4503 return NULL;
4504}
4505
Mike Stump11289f42009-09-09 15:08:12 +00004506/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004507/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004508/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004509int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004510 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4511 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004512
4513 // Unwrap enums to their underlying type.
4514 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4515 LHSC = getIntegerTypeForEnum(ET);
4516 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4517 RHSC = getIntegerTypeForEnum(ET);
4518
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004519 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004520
Chris Lattner76a00cf2008-04-06 22:59:24 +00004521 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4522 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004523
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004524 unsigned LHSRank = getIntegerRank(LHSC);
4525 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004526
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004527 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4528 if (LHSRank == RHSRank) return 0;
4529 return LHSRank > RHSRank ? 1 : -1;
4530 }
Mike Stump11289f42009-09-09 15:08:12 +00004531
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004532 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4533 if (LHSUnsigned) {
4534 // If the unsigned [LHS] type is larger, return it.
4535 if (LHSRank >= RHSRank)
4536 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004537
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004538 // If the signed type can represent all values of the unsigned type, it
4539 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004540 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004541 return -1;
4542 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004543
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004544 // If the unsigned [RHS] type is larger, return it.
4545 if (RHSRank >= LHSRank)
4546 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004547
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004548 // If the signed type can represent all values of the unsigned type, it
4549 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004550 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004551 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004552}
Anders Carlsson98f07902007-08-17 05:31:46 +00004553
Mike Stump11289f42009-09-09 15:08:12 +00004554// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004555QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004556 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004557 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004558 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004559
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004560 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004561
Anders Carlsson98f07902007-08-17 05:31:46 +00004562 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004563 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004564 // int flags;
4565 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004566 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004567 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004568 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004569 FieldTypes[3] = LongTy;
4570
Anders Carlsson98f07902007-08-17 05:31:46 +00004571 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004572 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004573 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004574 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004575 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004576 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004577 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004578 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004579 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004580 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004581 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004582 }
4583
Douglas Gregord5058122010-02-11 01:19:42 +00004584 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004585 }
Mike Stump11289f42009-09-09 15:08:12 +00004586
Anders Carlsson98f07902007-08-17 05:31:46 +00004587 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004588}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004589
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004590QualType ASTContext::getObjCSuperType() const {
4591 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004592 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004593 TUDecl->addDecl(ObjCSuperTypeDecl);
4594 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4595 }
4596 return ObjCSuperType;
4597}
4598
Douglas Gregor512b0772009-04-23 22:29:11 +00004599void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004600 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004601 assert(Rec && "Invalid CFConstantStringType");
4602 CFConstantStringTypeDecl = Rec->getDecl();
4603}
4604
Jay Foad39c79802011-01-12 09:06:06 +00004605QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004606 if (BlockDescriptorType)
4607 return getTagDeclType(BlockDescriptorType);
4608
Alp Toker2dea15b2013-12-17 01:22:38 +00004609 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004610 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004611 RD = buildImplicitRecord("__block_descriptor");
4612 RD->startDefinition();
4613
Mike Stumpd0153282009-10-20 02:12:22 +00004614 QualType FieldTypes[] = {
4615 UnsignedLongTy,
4616 UnsignedLongTy,
4617 };
4618
Craig Topperd6d31ac2013-07-15 08:24:27 +00004619 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004620 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004621 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004622 };
4623
4624 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004625 FieldDecl *Field = FieldDecl::Create(
4626 *this, RD, SourceLocation(), SourceLocation(),
4627 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4628 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004629 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004630 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004631 }
4632
Alp Toker2dea15b2013-12-17 01:22:38 +00004633 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004634
Alp Toker2dea15b2013-12-17 01:22:38 +00004635 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004636
4637 return getTagDeclType(BlockDescriptorType);
4638}
4639
Jay Foad39c79802011-01-12 09:06:06 +00004640QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004641 if (BlockDescriptorExtendedType)
4642 return getTagDeclType(BlockDescriptorExtendedType);
4643
Alp Toker2dea15b2013-12-17 01:22:38 +00004644 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004645 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004646 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4647 RD->startDefinition();
4648
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004649 QualType FieldTypes[] = {
4650 UnsignedLongTy,
4651 UnsignedLongTy,
4652 getPointerType(VoidPtrTy),
4653 getPointerType(VoidPtrTy)
4654 };
4655
Craig Topperd6d31ac2013-07-15 08:24:27 +00004656 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004657 "reserved",
4658 "Size",
4659 "CopyFuncPtr",
4660 "DestroyFuncPtr"
4661 };
4662
4663 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004664 FieldDecl *Field = FieldDecl::Create(
4665 *this, RD, SourceLocation(), SourceLocation(),
4666 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4667 /*BitWidth=*/0,
4668 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004669 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004670 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004671 }
4672
Alp Toker2dea15b2013-12-17 01:22:38 +00004673 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004674
Alp Toker2dea15b2013-12-17 01:22:38 +00004675 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004676 return getTagDeclType(BlockDescriptorExtendedType);
4677}
4678
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004679/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4680/// requires copy/dispose. Note that this must match the logic
4681/// in buildByrefHelpers.
4682bool ASTContext::BlockRequiresCopying(QualType Ty,
4683 const VarDecl *D) {
4684 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4685 const Expr *copyExpr = getBlockVarCopyInits(D);
4686 if (!copyExpr && record->hasTrivialDestructor()) return false;
4687
Mike Stump94967902009-10-21 18:16:27 +00004688 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004689 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004690
4691 if (!Ty->isObjCRetainableType()) return false;
4692
4693 Qualifiers qs = Ty.getQualifiers();
4694
4695 // If we have lifetime, that dominates.
4696 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4697 assert(getLangOpts().ObjCAutoRefCount);
4698
4699 switch (lifetime) {
4700 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4701
4702 // These are just bits as far as the runtime is concerned.
4703 case Qualifiers::OCL_ExplicitNone:
4704 case Qualifiers::OCL_Autoreleasing:
4705 return false;
4706
4707 // Tell the runtime that this is ARC __weak, called by the
4708 // byref routines.
4709 case Qualifiers::OCL_Weak:
4710 // ARC __strong __block variables need to be retained.
4711 case Qualifiers::OCL_Strong:
4712 return true;
4713 }
4714 llvm_unreachable("fell out of lifetime switch!");
4715 }
4716 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4717 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004718}
4719
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004720bool ASTContext::getByrefLifetime(QualType Ty,
4721 Qualifiers::ObjCLifetime &LifeTime,
4722 bool &HasByrefExtendedLayout) const {
4723
4724 if (!getLangOpts().ObjC1 ||
4725 getLangOpts().getGC() != LangOptions::NonGC)
4726 return false;
4727
4728 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004729 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004730 HasByrefExtendedLayout = true;
4731 LifeTime = Qualifiers::OCL_None;
4732 }
4733 else if (getLangOpts().ObjCAutoRefCount)
4734 LifeTime = Ty.getObjCLifetime();
4735 // MRR.
4736 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4737 LifeTime = Qualifiers::OCL_ExplicitNone;
4738 else
4739 LifeTime = Qualifiers::OCL_None;
4740 return true;
4741}
4742
Douglas Gregorbab8a962011-09-08 01:46:34 +00004743TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4744 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004745 ObjCInstanceTypeDecl =
4746 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004747 return ObjCInstanceTypeDecl;
4748}
4749
Anders Carlsson18acd442007-10-29 06:33:42 +00004750// This returns true if a type has been typedefed to BOOL:
4751// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004752static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004753 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004754 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4755 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004756
Anders Carlssond8499822007-10-29 05:01:08 +00004757 return false;
4758}
4759
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004760/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004761/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004762CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004763 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4764 return CharUnits::Zero();
4765
Ken Dyck40775002010-01-11 17:06:35 +00004766 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004767
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004768 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004769 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004770 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004771 // Treat arrays as pointers, since that's how they're passed in.
4772 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004773 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004774 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004775}
4776
4777static inline
4778std::string charUnitsToString(const CharUnits &CU) {
4779 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004780}
4781
John McCall351762c2011-02-07 10:33:21 +00004782/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004783/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004784std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4785 std::string S;
4786
David Chisnall950a9512009-11-17 19:33:30 +00004787 const BlockDecl *Decl = Expr->getBlockDecl();
4788 QualType BlockTy =
4789 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4790 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004791 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004792 getObjCEncodingForMethodParameter(
4793 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4794 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004795 else
Alp Toker314cc812014-01-25 16:55:45 +00004796 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004797 // Compute size of all parameters.
4798 // Start with computing size of a pointer in number of bytes.
4799 // FIXME: There might(should) be a better way of doing this computation!
4800 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004801 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4802 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004803 for (auto PI : Decl->params()) {
4804 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004805 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004806 if (sz.isZero())
4807 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004808 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004809 ParmOffset += sz;
4810 }
4811 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004812 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004813 // Block pointer and offset.
4814 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004815
4816 // Argument types.
4817 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004818 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004819 QualType PType = PVDecl->getOriginalType();
4820 if (const ArrayType *AT =
4821 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4822 // Use array's original type only if it has known number of
4823 // elements.
4824 if (!isa<ConstantArrayType>(AT))
4825 PType = PVDecl->getType();
4826 } else if (PType->isFunctionType())
4827 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004828 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004829 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4830 S, true /*Extended*/);
4831 else
4832 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004833 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004834 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004835 }
John McCall351762c2011-02-07 10:33:21 +00004836
4837 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004838}
4839
Douglas Gregora9d84932011-05-27 01:19:52 +00004840bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004841 std::string& S) {
4842 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004843 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004844 CharUnits ParmOffset;
4845 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004846 for (auto PI : Decl->params()) {
4847 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004848 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004849 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004850 continue;
4851
David Chisnall50e4eba2010-12-30 14:05:53 +00004852 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004853 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004854 ParmOffset += sz;
4855 }
4856 S += charUnitsToString(ParmOffset);
4857 ParmOffset = CharUnits::Zero();
4858
4859 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004860 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004861 QualType PType = PVDecl->getOriginalType();
4862 if (const ArrayType *AT =
4863 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4864 // Use array's original type only if it has known number of
4865 // elements.
4866 if (!isa<ConstantArrayType>(AT))
4867 PType = PVDecl->getType();
4868 } else if (PType->isFunctionType())
4869 PType = PVDecl->getType();
4870 getObjCEncodingForType(PType, S);
4871 S += charUnitsToString(ParmOffset);
4872 ParmOffset += getObjCEncodingTypeSize(PType);
4873 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004874
4875 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004876}
4877
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004878/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4879/// method parameter or return type. If Extended, include class names and
4880/// block object types.
4881void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4882 QualType T, std::string& S,
4883 bool Extended) const {
4884 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4885 getObjCEncodingForTypeQualifier(QT, S);
4886 // Encode parameter type.
4887 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4888 true /*OutermostType*/,
4889 false /*EncodingProperty*/,
4890 false /*StructField*/,
4891 Extended /*EncodeBlockParameters*/,
4892 Extended /*EncodeClassNames*/);
4893}
4894
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004895/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004896/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004897bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004898 std::string& S,
4899 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004900 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004901 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004902 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4903 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004904 // Compute size of all parameters.
4905 // Start with computing size of a pointer in number of bytes.
4906 // FIXME: There might(should) be a better way of doing this computation!
4907 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004908 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004909 // The first two arguments (self and _cmd) are pointers; account for
4910 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004911 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004912 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004913 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004914 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004915 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004916 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004917 continue;
4918
Ken Dyck40775002010-01-11 17:06:35 +00004919 assert (sz.isPositive() &&
4920 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004921 ParmOffset += sz;
4922 }
Ken Dyck40775002010-01-11 17:06:35 +00004923 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004924 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004925 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004926
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004927 // Argument types.
4928 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004929 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004930 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004931 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004932 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004933 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004934 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4935 // Use array's original type only if it has known number of
4936 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004937 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004938 PType = PVDecl->getType();
4939 } else if (PType->isFunctionType())
4940 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004941 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4942 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004943 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004944 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004945 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004946
4947 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004948}
4949
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004950ObjCPropertyImplDecl *
4951ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4952 const ObjCPropertyDecl *PD,
4953 const Decl *Container) const {
4954 if (!Container)
4955 return 0;
4956 if (const ObjCCategoryImplDecl *CID =
4957 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4958 for (ObjCCategoryImplDecl::propimpl_iterator
4959 i = CID->propimpl_begin(), e = CID->propimpl_end();
4960 i != e; ++i) {
4961 ObjCPropertyImplDecl *PID = *i;
4962 if (PID->getPropertyDecl() == PD)
4963 return PID;
4964 }
4965 } else {
4966 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4967 for (ObjCCategoryImplDecl::propimpl_iterator
4968 i = OID->propimpl_begin(), e = OID->propimpl_end();
4969 i != e; ++i) {
4970 ObjCPropertyImplDecl *PID = *i;
4971 if (PID->getPropertyDecl() == PD)
4972 return PID;
4973 }
4974 }
4975 return 0;
4976}
4977
Daniel Dunbar4932b362008-08-28 04:38:10 +00004978/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004979/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004980/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4981/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004982/// Property attributes are stored as a comma-delimited C string. The simple
4983/// attributes readonly and bycopy are encoded as single characters. The
4984/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4985/// encoded as single characters, followed by an identifier. Property types
4986/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004987/// these attributes are defined by the following enumeration:
4988/// @code
4989/// enum PropertyAttributes {
4990/// kPropertyReadOnly = 'R', // property is read-only.
4991/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4992/// kPropertyByref = '&', // property is a reference to the value last assigned
4993/// kPropertyDynamic = 'D', // property is dynamic
4994/// kPropertyGetter = 'G', // followed by getter selector name
4995/// kPropertySetter = 'S', // followed by setter selector name
4996/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004997/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004998/// kPropertyWeak = 'W' // 'weak' property
4999/// kPropertyStrong = 'P' // property GC'able
5000/// kPropertyNonAtomic = 'N' // property non-atomic
5001/// };
5002/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005003void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005004 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005005 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005006 // Collect information from the property implementation decl(s).
5007 bool Dynamic = false;
5008 ObjCPropertyImplDecl *SynthesizePID = 0;
5009
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005010 if (ObjCPropertyImplDecl *PropertyImpDecl =
5011 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5012 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5013 Dynamic = true;
5014 else
5015 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005016 }
5017
5018 // FIXME: This is not very efficient.
5019 S = "T";
5020
5021 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005022 // GCC has some special rules regarding encoding of properties which
5023 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005024 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005025 true /* outermost type */,
5026 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005027
5028 if (PD->isReadOnly()) {
5029 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005030 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5031 S += ",C";
5032 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5033 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005034 } else {
5035 switch (PD->getSetterKind()) {
5036 case ObjCPropertyDecl::Assign: break;
5037 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005038 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005039 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005040 }
5041 }
5042
5043 // It really isn't clear at all what this means, since properties
5044 // are "dynamic by default".
5045 if (Dynamic)
5046 S += ",D";
5047
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005048 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5049 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005050
Daniel Dunbar4932b362008-08-28 04:38:10 +00005051 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5052 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005053 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005054 }
5055
5056 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5057 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005058 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005059 }
5060
5061 if (SynthesizePID) {
5062 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5063 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005064 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005065 }
5066
5067 // FIXME: OBJCGC: weak & strong
5068}
5069
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005070/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005071/// Another legacy compatibility encoding: 32-bit longs are encoded as
5072/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005073/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5074///
5075void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005076 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005077 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005078 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005079 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005080 else
Jay Foad39c79802011-01-12 09:06:06 +00005081 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005082 PointeeTy = IntTy;
5083 }
5084 }
5085}
5086
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005087void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005088 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005089 // We follow the behavior of gcc, expanding structures which are
5090 // directly pointed to, and expanding embedded structures. Note that
5091 // these rules are sufficient to prevent recursive encoding of the
5092 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005093 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005094 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005095}
5096
John McCall393a78d2012-12-20 02:45:14 +00005097static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5098 BuiltinType::Kind kind) {
5099 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005100 case BuiltinType::Void: return 'v';
5101 case BuiltinType::Bool: return 'B';
5102 case BuiltinType::Char_U:
5103 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005104 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005105 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005106 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005107 case BuiltinType::UInt: return 'I';
5108 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005109 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005110 case BuiltinType::UInt128: return 'T';
5111 case BuiltinType::ULongLong: return 'Q';
5112 case BuiltinType::Char_S:
5113 case BuiltinType::SChar: return 'c';
5114 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005115 case BuiltinType::WChar_S:
5116 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005117 case BuiltinType::Int: return 'i';
5118 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005119 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005120 case BuiltinType::LongLong: return 'q';
5121 case BuiltinType::Int128: return 't';
5122 case BuiltinType::Float: return 'f';
5123 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005124 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005125 case BuiltinType::NullPtr: return '*'; // like char*
5126
5127 case BuiltinType::Half:
5128 // FIXME: potentially need @encodes for these!
5129 return ' ';
5130
5131 case BuiltinType::ObjCId:
5132 case BuiltinType::ObjCClass:
5133 case BuiltinType::ObjCSel:
5134 llvm_unreachable("@encoding ObjC primitive type");
5135
5136 // OpenCL and placeholder types don't need @encodings.
5137 case BuiltinType::OCLImage1d:
5138 case BuiltinType::OCLImage1dArray:
5139 case BuiltinType::OCLImage1dBuffer:
5140 case BuiltinType::OCLImage2d:
5141 case BuiltinType::OCLImage2dArray:
5142 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005143 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005144 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005145 case BuiltinType::Dependent:
5146#define BUILTIN_TYPE(KIND, ID)
5147#define PLACEHOLDER_TYPE(KIND, ID) \
5148 case BuiltinType::KIND:
5149#include "clang/AST/BuiltinTypes.def"
5150 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005151 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005152 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005153}
5154
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005155static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5156 EnumDecl *Enum = ET->getDecl();
5157
5158 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5159 if (!Enum->isFixed())
5160 return 'i';
5161
5162 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005163 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5164 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005165}
5166
Jay Foad39c79802011-01-12 09:06:06 +00005167static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005168 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005169 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005170 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005171 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5172 // The GNU runtime requires more information; bitfields are encoded as b,
5173 // then the offset (in bits) of the first element, then the type of the
5174 // bitfield, then the size in bits. For example, in this structure:
5175 //
5176 // struct
5177 // {
5178 // int integer;
5179 // int flags:2;
5180 // };
5181 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5182 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5183 // information is not especially sensible, but we're stuck with it for
5184 // compatibility with GCC, although providing it breaks anything that
5185 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005186 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005187 const RecordDecl *RD = FD->getParent();
5188 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005189 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005190 if (const EnumType *ET = T->getAs<EnumType>())
5191 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005192 else {
5193 const BuiltinType *BT = T->castAs<BuiltinType>();
5194 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5195 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005196 }
Richard Smithcaf33902011-10-10 18:28:20 +00005197 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005198}
5199
Daniel Dunbar07d07852009-10-18 21:17:35 +00005200// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005201void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5202 bool ExpandPointedToStructures,
5203 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005204 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005205 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005206 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005207 bool StructField,
5208 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005209 bool EncodeClassNames,
5210 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005211 CanQualType CT = getCanonicalType(T);
5212 switch (CT->getTypeClass()) {
5213 case Type::Builtin:
5214 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005215 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005216 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005217 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5218 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5219 else
5220 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005221 return;
Mike Stump11289f42009-09-09 15:08:12 +00005222
John McCall393a78d2012-12-20 02:45:14 +00005223 case Type::Complex: {
5224 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005225 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005226 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005227 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005228 return;
5229 }
John McCall393a78d2012-12-20 02:45:14 +00005230
5231 case Type::Atomic: {
5232 const AtomicType *AT = T->castAs<AtomicType>();
5233 S += 'A';
5234 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5235 false, false);
5236 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005237 }
John McCall393a78d2012-12-20 02:45:14 +00005238
5239 // encoding for pointer or reference types.
5240 case Type::Pointer:
5241 case Type::LValueReference:
5242 case Type::RValueReference: {
5243 QualType PointeeTy;
5244 if (isa<PointerType>(CT)) {
5245 const PointerType *PT = T->castAs<PointerType>();
5246 if (PT->isObjCSelType()) {
5247 S += ':';
5248 return;
5249 }
5250 PointeeTy = PT->getPointeeType();
5251 } else {
5252 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5253 }
5254
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005255 bool isReadOnly = false;
5256 // For historical/compatibility reasons, the read-only qualifier of the
5257 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5258 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005259 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005260 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005261 if (OutermostType && T.isConstQualified()) {
5262 isReadOnly = true;
5263 S += 'r';
5264 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005265 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005266 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005267 while (P->getAs<PointerType>())
5268 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005269 if (P.isConstQualified()) {
5270 isReadOnly = true;
5271 S += 'r';
5272 }
5273 }
5274 if (isReadOnly) {
5275 // Another legacy compatibility encoding. Some ObjC qualifier and type
5276 // combinations need to be rearranged.
5277 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005278 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005279 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005280 }
Mike Stump11289f42009-09-09 15:08:12 +00005281
Anders Carlssond8499822007-10-29 05:01:08 +00005282 if (PointeeTy->isCharType()) {
5283 // char pointer types should be encoded as '*' unless it is a
5284 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005285 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005286 S += '*';
5287 return;
5288 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005289 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005290 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5291 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5292 S += '#';
5293 return;
5294 }
5295 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5296 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5297 S += '@';
5298 return;
5299 }
5300 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005301 }
Anders Carlssond8499822007-10-29 05:01:08 +00005302 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005303 getLegacyIntegralTypeEncoding(PointeeTy);
5304
Mike Stump11289f42009-09-09 15:08:12 +00005305 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005306 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005307 return;
5308 }
John McCall393a78d2012-12-20 02:45:14 +00005309
5310 case Type::ConstantArray:
5311 case Type::IncompleteArray:
5312 case Type::VariableArray: {
5313 const ArrayType *AT = cast<ArrayType>(CT);
5314
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005315 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005316 // Incomplete arrays are encoded as a pointer to the array element.
5317 S += '^';
5318
Mike Stump11289f42009-09-09 15:08:12 +00005319 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005320 false, ExpandStructures, FD);
5321 } else {
5322 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005323
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005324 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5325 S += llvm::utostr(CAT->getSize().getZExtValue());
5326 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005327 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005328 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5329 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005330 S += '0';
5331 }
Mike Stump11289f42009-09-09 15:08:12 +00005332
5333 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005334 false, ExpandStructures, FD);
5335 S += ']';
5336 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005337 return;
5338 }
Mike Stump11289f42009-09-09 15:08:12 +00005339
John McCall393a78d2012-12-20 02:45:14 +00005340 case Type::FunctionNoProto:
5341 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005342 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005343 return;
Mike Stump11289f42009-09-09 15:08:12 +00005344
John McCall393a78d2012-12-20 02:45:14 +00005345 case Type::Record: {
5346 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005347 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005348 // Anonymous structures print as '?'
5349 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5350 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005351 if (ClassTemplateSpecializationDecl *Spec
5352 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5353 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005354 llvm::raw_string_ostream OS(S);
5355 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005356 TemplateArgs.data(),
5357 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005358 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005359 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005360 } else {
5361 S += '?';
5362 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005363 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005364 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005365 if (!RDecl->isUnion()) {
5366 getObjCEncodingForStructureImpl(RDecl, S, FD);
5367 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005368 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005369 if (FD) {
5370 S += '"';
5371 S += Field->getNameAsString();
5372 S += '"';
5373 }
Mike Stump11289f42009-09-09 15:08:12 +00005374
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005375 // Special case bit-fields.
5376 if (Field->isBitField()) {
5377 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005378 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005379 } else {
5380 QualType qt = Field->getType();
5381 getLegacyIntegralTypeEncoding(qt);
5382 getObjCEncodingForTypeImpl(qt, S, false, true,
5383 FD, /*OutermostType*/false,
5384 /*EncodingProperty*/false,
5385 /*StructField*/true);
5386 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005387 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005388 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005389 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005390 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005391 return;
5392 }
Mike Stump11289f42009-09-09 15:08:12 +00005393
John McCall393a78d2012-12-20 02:45:14 +00005394 case Type::BlockPointer: {
5395 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005396 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005397 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005398 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005399
5400 S += '<';
5401 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005402 getObjCEncodingForTypeImpl(
5403 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5404 FD, false /* OutermostType */, EncodingProperty,
5405 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005406 // Block self
5407 S += "@?";
5408 // Block parameters
5409 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005410 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5411 E = FPT->param_type_end();
5412 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005413 getObjCEncodingForTypeImpl(*I, S,
5414 ExpandPointedToStructures,
5415 ExpandStructures,
5416 FD,
5417 false /* OutermostType */,
5418 EncodingProperty,
5419 false /* StructField */,
5420 EncodeBlockParameters,
5421 EncodeClassNames);
5422 }
5423 }
5424 S += '>';
5425 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005426 return;
5427 }
Mike Stump11289f42009-09-09 15:08:12 +00005428
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005429 case Type::ObjCObject: {
5430 // hack to match legacy encoding of *id and *Class
5431 QualType Ty = getObjCObjectPointerType(CT);
5432 if (Ty->isObjCIdType()) {
5433 S += "{objc_object=}";
5434 return;
5435 }
5436 else if (Ty->isObjCClassType()) {
5437 S += "{objc_class=}";
5438 return;
5439 }
5440 }
5441
John McCall393a78d2012-12-20 02:45:14 +00005442 case Type::ObjCInterface: {
5443 // Ignore protocol qualifiers when mangling at this level.
5444 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005445
John McCall393a78d2012-12-20 02:45:14 +00005446 // The assumption seems to be that this assert will succeed
5447 // because nested levels will have filtered out 'id' and 'Class'.
5448 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005449 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005450 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005451 S += '{';
5452 const IdentifierInfo *II = OI->getIdentifier();
5453 S += II->getName();
5454 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005455 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005456 DeepCollectObjCIvars(OI, true, Ivars);
5457 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005458 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005459 if (Field->isBitField())
5460 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005461 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005462 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5463 false, false, false, false, false,
5464 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005465 }
5466 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005467 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005468 }
Mike Stump11289f42009-09-09 15:08:12 +00005469
John McCall393a78d2012-12-20 02:45:14 +00005470 case Type::ObjCObjectPointer: {
5471 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005472 if (OPT->isObjCIdType()) {
5473 S += '@';
5474 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005475 }
Mike Stump11289f42009-09-09 15:08:12 +00005476
Steve Narofff0c86112009-10-28 22:03:49 +00005477 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5478 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5479 // Since this is a binary compatibility issue, need to consult with runtime
5480 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005481 S += '#';
5482 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005483 }
Mike Stump11289f42009-09-09 15:08:12 +00005484
Chris Lattnere7cabb92009-07-13 00:10:46 +00005485 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005486 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005487 ExpandPointedToStructures,
5488 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005489 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005490 // Note that we do extended encoding of protocol qualifer list
5491 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005492 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005493 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5494 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005495 S += '<';
5496 S += (*I)->getNameAsString();
5497 S += '>';
5498 }
5499 S += '"';
5500 }
5501 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005502 }
Mike Stump11289f42009-09-09 15:08:12 +00005503
Chris Lattnere7cabb92009-07-13 00:10:46 +00005504 QualType PointeeTy = OPT->getPointeeType();
5505 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005506 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5507 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005508 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005509 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005510 // {...};
5511 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005512 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005513 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005514 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5515 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5516 DeepCollectObjCIvars(OI, true, Ivars);
5517 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5518 if (cast<FieldDecl>(Ivars[i]) == FD) {
5519 S += '{';
5520 S += OI->getIdentifier()->getName();
5521 S += '}';
5522 return;
5523 }
5524 }
5525 }
Mike Stump11289f42009-09-09 15:08:12 +00005526 getObjCEncodingForTypeImpl(PointeeTy, S,
5527 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005528 NULL,
5529 false, false, false, false, false,
5530 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005531 return;
5532 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005533
5534 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005535 if (OPT->getInterfaceDecl() &&
5536 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005537 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005538 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005539 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5540 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005541 S += '<';
5542 S += (*I)->getNameAsString();
5543 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005544 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005545 S += '"';
5546 }
5547 return;
5548 }
Mike Stump11289f42009-09-09 15:08:12 +00005549
John McCalla9e6e8d2010-05-17 23:56:34 +00005550 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005551 // FIXME: we shoul do better than that. 'M' is available.
5552 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005553 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005554
John McCall393a78d2012-12-20 02:45:14 +00005555 case Type::Vector:
5556 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005557 // This matches gcc's encoding, even though technically it is
5558 // insufficient.
5559 // FIXME. We should do a better job than gcc.
5560 return;
John McCall393a78d2012-12-20 02:45:14 +00005561
Richard Smith27d807c2013-04-30 13:56:41 +00005562 case Type::Auto:
5563 // We could see an undeduced auto type here during error recovery.
5564 // Just ignore it.
5565 return;
5566
John McCall393a78d2012-12-20 02:45:14 +00005567#define ABSTRACT_TYPE(KIND, BASE)
5568#define TYPE(KIND, BASE)
5569#define DEPENDENT_TYPE(KIND, BASE) \
5570 case Type::KIND:
5571#define NON_CANONICAL_TYPE(KIND, BASE) \
5572 case Type::KIND:
5573#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5574 case Type::KIND:
5575#include "clang/AST/TypeNodes.def"
5576 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005577 }
John McCall393a78d2012-12-20 02:45:14 +00005578 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005579}
5580
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005581void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5582 std::string &S,
5583 const FieldDecl *FD,
5584 bool includeVBases) const {
5585 assert(RDecl && "Expected non-null RecordDecl");
5586 assert(!RDecl->isUnion() && "Should not be called for unions");
5587 if (!RDecl->getDefinition())
5588 return;
5589
5590 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5591 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5592 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5593
5594 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005595 for (const auto &BI : CXXRec->bases()) {
5596 if (!BI.isVirtual()) {
5597 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005598 if (base->isEmpty())
5599 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005600 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005601 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5602 std::make_pair(offs, base));
5603 }
5604 }
5605 }
5606
5607 unsigned i = 0;
5608 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5609 FieldEnd = RDecl->field_end();
5610 Field != FieldEnd; ++Field, ++i) {
5611 uint64_t offs = layout.getFieldOffset(i);
5612 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005613 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005614 }
5615
5616 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005617 for (const auto &BI : CXXRec->vbases()) {
5618 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005619 if (base->isEmpty())
5620 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005621 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005622 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5623 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005624 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5625 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005626 }
5627 }
5628
5629 CharUnits size;
5630 if (CXXRec) {
5631 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5632 } else {
5633 size = layout.getSize();
5634 }
5635
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005636#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005637 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005638#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005639 std::multimap<uint64_t, NamedDecl *>::iterator
5640 CurLayObj = FieldOrBaseOffsets.begin();
5641
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005642 if (CXXRec && CXXRec->isDynamicClass() &&
5643 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005644 if (FD) {
5645 S += "\"_vptr$";
5646 std::string recname = CXXRec->getNameAsString();
5647 if (recname.empty()) recname = "?";
5648 S += recname;
5649 S += '"';
5650 }
5651 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005652#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005653 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005654#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005655 }
5656
5657 if (!RDecl->hasFlexibleArrayMember()) {
5658 // Mark the end of the structure.
5659 uint64_t offs = toBits(size);
5660 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5661 std::make_pair(offs, (NamedDecl*)0));
5662 }
5663
5664 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005665#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005666 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005667 if (CurOffs < CurLayObj->first) {
5668 uint64_t padding = CurLayObj->first - CurOffs;
5669 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5670 // packing/alignment of members is different that normal, in which case
5671 // the encoding will be out-of-sync with the real layout.
5672 // If the runtime switches to just consider the size of types without
5673 // taking into account alignment, we could make padding explicit in the
5674 // encoding (e.g. using arrays of chars). The encoding strings would be
5675 // longer then though.
5676 CurOffs += padding;
5677 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005678#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005679
5680 NamedDecl *dcl = CurLayObj->second;
5681 if (dcl == 0)
5682 break; // reached end of structure.
5683
5684 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5685 // We expand the bases without their virtual bases since those are going
5686 // in the initial structure. Note that this differs from gcc which
5687 // expands virtual bases each time one is encountered in the hierarchy,
5688 // making the encoding type bigger than it really is.
5689 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005690 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005691#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005692 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005693#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005694 } else {
5695 FieldDecl *field = cast<FieldDecl>(dcl);
5696 if (FD) {
5697 S += '"';
5698 S += field->getNameAsString();
5699 S += '"';
5700 }
5701
5702 if (field->isBitField()) {
5703 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005704#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005705 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005706#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005707 } else {
5708 QualType qt = field->getType();
5709 getLegacyIntegralTypeEncoding(qt);
5710 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5711 /*OutermostType*/false,
5712 /*EncodingProperty*/false,
5713 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005714#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005715 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005716#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005717 }
5718 }
5719 }
5720}
5721
Mike Stump11289f42009-09-09 15:08:12 +00005722void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005723 std::string& S) const {
5724 if (QT & Decl::OBJC_TQ_In)
5725 S += 'n';
5726 if (QT & Decl::OBJC_TQ_Inout)
5727 S += 'N';
5728 if (QT & Decl::OBJC_TQ_Out)
5729 S += 'o';
5730 if (QT & Decl::OBJC_TQ_Bycopy)
5731 S += 'O';
5732 if (QT & Decl::OBJC_TQ_Byref)
5733 S += 'R';
5734 if (QT & Decl::OBJC_TQ_Oneway)
5735 S += 'V';
5736}
5737
Douglas Gregor3ea72692011-08-12 05:46:01 +00005738TypedefDecl *ASTContext::getObjCIdDecl() const {
5739 if (!ObjCIdDecl) {
5740 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5741 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005742 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005743 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005744 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005745}
5746
Douglas Gregor52e02802011-08-12 06:17:30 +00005747TypedefDecl *ASTContext::getObjCSelDecl() const {
5748 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005749 QualType T = getPointerType(ObjCBuiltinSelTy);
5750 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005751 }
5752 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005753}
5754
Douglas Gregor0a586182011-08-12 05:59:41 +00005755TypedefDecl *ASTContext::getObjCClassDecl() const {
5756 if (!ObjCClassDecl) {
5757 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5758 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005759 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005760 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005761 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005762}
5763
Douglas Gregord53ae832012-01-17 18:09:05 +00005764ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5765 if (!ObjCProtocolClassDecl) {
5766 ObjCProtocolClassDecl
5767 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5768 SourceLocation(),
5769 &Idents.get("Protocol"),
5770 /*PrevDecl=*/0,
5771 SourceLocation(), true);
5772 }
5773
5774 return ObjCProtocolClassDecl;
5775}
5776
Meador Inge5d3fb222012-06-16 03:34:49 +00005777//===----------------------------------------------------------------------===//
5778// __builtin_va_list Construction Functions
5779//===----------------------------------------------------------------------===//
5780
5781static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5782 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005783 QualType T = Context->getPointerType(Context->CharTy);
5784 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005785}
5786
5787static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5788 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005789 QualType T = Context->getPointerType(Context->VoidTy);
5790 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005791}
5792
Tim Northover9bb857a2013-01-31 12:13:10 +00005793static TypedefDecl *
5794CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005795 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005796 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005797 if (Context->getLangOpts().CPlusPlus) {
5798 // namespace std { struct __va_list {
5799 NamespaceDecl *NS;
5800 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5801 Context->getTranslationUnitDecl(),
5802 /*Inline*/false, SourceLocation(),
5803 SourceLocation(), &Context->Idents.get("std"),
5804 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005805 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005806 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005807 }
5808
5809 VaListTagDecl->startDefinition();
5810
5811 const size_t NumFields = 5;
5812 QualType FieldTypes[NumFields];
5813 const char *FieldNames[NumFields];
5814
5815 // void *__stack;
5816 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5817 FieldNames[0] = "__stack";
5818
5819 // void *__gr_top;
5820 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5821 FieldNames[1] = "__gr_top";
5822
5823 // void *__vr_top;
5824 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5825 FieldNames[2] = "__vr_top";
5826
5827 // int __gr_offs;
5828 FieldTypes[3] = Context->IntTy;
5829 FieldNames[3] = "__gr_offs";
5830
5831 // int __vr_offs;
5832 FieldTypes[4] = Context->IntTy;
5833 FieldNames[4] = "__vr_offs";
5834
5835 // Create fields
5836 for (unsigned i = 0; i < NumFields; ++i) {
5837 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5838 VaListTagDecl,
5839 SourceLocation(),
5840 SourceLocation(),
5841 &Context->Idents.get(FieldNames[i]),
5842 FieldTypes[i], /*TInfo=*/0,
5843 /*BitWidth=*/0,
5844 /*Mutable=*/false,
5845 ICIS_NoInit);
5846 Field->setAccess(AS_public);
5847 VaListTagDecl->addDecl(Field);
5848 }
5849 VaListTagDecl->completeDefinition();
5850 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5851 Context->VaListTagTy = VaListTagType;
5852
5853 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005854 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005855}
5856
Meador Inge5d3fb222012-06-16 03:34:49 +00005857static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5858 // typedef struct __va_list_tag {
5859 RecordDecl *VaListTagDecl;
5860
Alp Toker2dea15b2013-12-17 01:22:38 +00005861 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005862 VaListTagDecl->startDefinition();
5863
5864 const size_t NumFields = 5;
5865 QualType FieldTypes[NumFields];
5866 const char *FieldNames[NumFields];
5867
5868 // unsigned char gpr;
5869 FieldTypes[0] = Context->UnsignedCharTy;
5870 FieldNames[0] = "gpr";
5871
5872 // unsigned char fpr;
5873 FieldTypes[1] = Context->UnsignedCharTy;
5874 FieldNames[1] = "fpr";
5875
5876 // unsigned short reserved;
5877 FieldTypes[2] = Context->UnsignedShortTy;
5878 FieldNames[2] = "reserved";
5879
5880 // void* overflow_arg_area;
5881 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5882 FieldNames[3] = "overflow_arg_area";
5883
5884 // void* reg_save_area;
5885 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5886 FieldNames[4] = "reg_save_area";
5887
5888 // Create fields
5889 for (unsigned i = 0; i < NumFields; ++i) {
5890 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5891 SourceLocation(),
5892 SourceLocation(),
5893 &Context->Idents.get(FieldNames[i]),
5894 FieldTypes[i], /*TInfo=*/0,
5895 /*BitWidth=*/0,
5896 /*Mutable=*/false,
5897 ICIS_NoInit);
5898 Field->setAccess(AS_public);
5899 VaListTagDecl->addDecl(Field);
5900 }
5901 VaListTagDecl->completeDefinition();
5902 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005903 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005904
5905 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005906 TypedefDecl *VaListTagTypedefDecl =
5907 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5908
Meador Inge5d3fb222012-06-16 03:34:49 +00005909 QualType VaListTagTypedefType =
5910 Context->getTypedefType(VaListTagTypedefDecl);
5911
5912 // typedef __va_list_tag __builtin_va_list[1];
5913 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5914 QualType VaListTagArrayType
5915 = Context->getConstantArrayType(VaListTagTypedefType,
5916 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005917 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005918}
5919
5920static TypedefDecl *
5921CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5922 // typedef struct __va_list_tag {
5923 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005924 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005925 VaListTagDecl->startDefinition();
5926
5927 const size_t NumFields = 4;
5928 QualType FieldTypes[NumFields];
5929 const char *FieldNames[NumFields];
5930
5931 // unsigned gp_offset;
5932 FieldTypes[0] = Context->UnsignedIntTy;
5933 FieldNames[0] = "gp_offset";
5934
5935 // unsigned fp_offset;
5936 FieldTypes[1] = Context->UnsignedIntTy;
5937 FieldNames[1] = "fp_offset";
5938
5939 // void* overflow_arg_area;
5940 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5941 FieldNames[2] = "overflow_arg_area";
5942
5943 // void* reg_save_area;
5944 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5945 FieldNames[3] = "reg_save_area";
5946
5947 // Create fields
5948 for (unsigned i = 0; i < NumFields; ++i) {
5949 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5950 VaListTagDecl,
5951 SourceLocation(),
5952 SourceLocation(),
5953 &Context->Idents.get(FieldNames[i]),
5954 FieldTypes[i], /*TInfo=*/0,
5955 /*BitWidth=*/0,
5956 /*Mutable=*/false,
5957 ICIS_NoInit);
5958 Field->setAccess(AS_public);
5959 VaListTagDecl->addDecl(Field);
5960 }
5961 VaListTagDecl->completeDefinition();
5962 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005963 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005964
5965 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005966 TypedefDecl *VaListTagTypedefDecl =
5967 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5968
Meador Inge5d3fb222012-06-16 03:34:49 +00005969 QualType VaListTagTypedefType =
5970 Context->getTypedefType(VaListTagTypedefDecl);
5971
5972 // typedef __va_list_tag __builtin_va_list[1];
5973 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5974 QualType VaListTagArrayType
5975 = Context->getConstantArrayType(VaListTagTypedefType,
5976 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005977 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005978}
5979
5980static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5981 // typedef int __builtin_va_list[4];
5982 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5983 QualType IntArrayType
5984 = Context->getConstantArrayType(Context->IntTy,
5985 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005986 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005987}
5988
Logan Chien57086ce2012-10-10 06:56:20 +00005989static TypedefDecl *
5990CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005991 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005992 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005993 if (Context->getLangOpts().CPlusPlus) {
5994 // namespace std { struct __va_list {
5995 NamespaceDecl *NS;
5996 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5997 Context->getTranslationUnitDecl(),
5998 /*Inline*/false, SourceLocation(),
5999 SourceLocation(), &Context->Idents.get("std"),
6000 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006001 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006002 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006003 }
6004
6005 VaListDecl->startDefinition();
6006
6007 // void * __ap;
6008 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6009 VaListDecl,
6010 SourceLocation(),
6011 SourceLocation(),
6012 &Context->Idents.get("__ap"),
6013 Context->getPointerType(Context->VoidTy),
6014 /*TInfo=*/0,
6015 /*BitWidth=*/0,
6016 /*Mutable=*/false,
6017 ICIS_NoInit);
6018 Field->setAccess(AS_public);
6019 VaListDecl->addDecl(Field);
6020
6021 // };
6022 VaListDecl->completeDefinition();
6023
6024 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006025 QualType T = Context->getRecordType(VaListDecl);
6026 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006027}
6028
Ulrich Weigand47445072013-05-06 16:26:41 +00006029static TypedefDecl *
6030CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6031 // typedef struct __va_list_tag {
6032 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006033 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006034 VaListTagDecl->startDefinition();
6035
6036 const size_t NumFields = 4;
6037 QualType FieldTypes[NumFields];
6038 const char *FieldNames[NumFields];
6039
6040 // long __gpr;
6041 FieldTypes[0] = Context->LongTy;
6042 FieldNames[0] = "__gpr";
6043
6044 // long __fpr;
6045 FieldTypes[1] = Context->LongTy;
6046 FieldNames[1] = "__fpr";
6047
6048 // void *__overflow_arg_area;
6049 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6050 FieldNames[2] = "__overflow_arg_area";
6051
6052 // void *__reg_save_area;
6053 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6054 FieldNames[3] = "__reg_save_area";
6055
6056 // Create fields
6057 for (unsigned i = 0; i < NumFields; ++i) {
6058 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6059 VaListTagDecl,
6060 SourceLocation(),
6061 SourceLocation(),
6062 &Context->Idents.get(FieldNames[i]),
6063 FieldTypes[i], /*TInfo=*/0,
6064 /*BitWidth=*/0,
6065 /*Mutable=*/false,
6066 ICIS_NoInit);
6067 Field->setAccess(AS_public);
6068 VaListTagDecl->addDecl(Field);
6069 }
6070 VaListTagDecl->completeDefinition();
6071 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6072 Context->VaListTagTy = VaListTagType;
6073
6074 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006075 TypedefDecl *VaListTagTypedefDecl =
6076 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006077 QualType VaListTagTypedefType =
6078 Context->getTypedefType(VaListTagTypedefDecl);
6079
6080 // typedef __va_list_tag __builtin_va_list[1];
6081 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6082 QualType VaListTagArrayType
6083 = Context->getConstantArrayType(VaListTagTypedefType,
6084 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006085
Alp Toker56b5cc92013-12-15 10:36:26 +00006086 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006087}
6088
Meador Inge5d3fb222012-06-16 03:34:49 +00006089static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6090 TargetInfo::BuiltinVaListKind Kind) {
6091 switch (Kind) {
6092 case TargetInfo::CharPtrBuiltinVaList:
6093 return CreateCharPtrBuiltinVaListDecl(Context);
6094 case TargetInfo::VoidPtrBuiltinVaList:
6095 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006096 case TargetInfo::AArch64ABIBuiltinVaList:
6097 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006098 case TargetInfo::PowerABIBuiltinVaList:
6099 return CreatePowerABIBuiltinVaListDecl(Context);
6100 case TargetInfo::X86_64ABIBuiltinVaList:
6101 return CreateX86_64ABIBuiltinVaListDecl(Context);
6102 case TargetInfo::PNaClABIBuiltinVaList:
6103 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006104 case TargetInfo::AAPCSABIBuiltinVaList:
6105 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006106 case TargetInfo::SystemZBuiltinVaList:
6107 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006108 }
6109
6110 llvm_unreachable("Unhandled __builtin_va_list type kind");
6111}
6112
6113TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006114 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006115 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006116 assert(BuiltinVaListDecl->isImplicit());
6117 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006118
6119 return BuiltinVaListDecl;
6120}
6121
Meador Ingecfb60902012-07-01 15:57:25 +00006122QualType ASTContext::getVaListTagType() const {
6123 // Force the creation of VaListTagTy by building the __builtin_va_list
6124 // declaration.
6125 if (VaListTagTy.isNull())
6126 (void) getBuiltinVaListDecl();
6127
6128 return VaListTagTy;
6129}
6130
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006131void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006132 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006133 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006134
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006135 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006136}
6137
John McCalld28ae272009-12-02 08:04:21 +00006138/// \brief Retrieve the template name that corresponds to a non-empty
6139/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006140TemplateName
6141ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6142 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006143 unsigned size = End - Begin;
6144 assert(size > 1 && "set is not overloaded!");
6145
6146 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6147 size * sizeof(FunctionTemplateDecl*));
6148 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6149
6150 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006151 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006152 NamedDecl *D = *I;
6153 assert(isa<FunctionTemplateDecl>(D) ||
6154 (isa<UsingShadowDecl>(D) &&
6155 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6156 *Storage++ = D;
6157 }
6158
6159 return TemplateName(OT);
6160}
6161
Douglas Gregordc572a32009-03-30 22:58:21 +00006162/// \brief Retrieve the template name that represents a qualified
6163/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006164TemplateName
6165ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6166 bool TemplateKeyword,
6167 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006168 assert(NNS && "Missing nested-name-specifier in qualified template name");
6169
Douglas Gregorc42075a2010-02-04 18:10:26 +00006170 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006171 llvm::FoldingSetNodeID ID;
6172 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6173
6174 void *InsertPos = 0;
6175 QualifiedTemplateName *QTN =
6176 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6177 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006178 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6179 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006180 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6181 }
6182
6183 return TemplateName(QTN);
6184}
6185
6186/// \brief Retrieve the template name that represents a dependent
6187/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006188TemplateName
6189ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6190 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006191 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006192 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006193
6194 llvm::FoldingSetNodeID ID;
6195 DependentTemplateName::Profile(ID, NNS, Name);
6196
6197 void *InsertPos = 0;
6198 DependentTemplateName *QTN =
6199 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6200
6201 if (QTN)
6202 return TemplateName(QTN);
6203
6204 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6205 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006206 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6207 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006208 } else {
6209 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006210 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6211 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006212 DependentTemplateName *CheckQTN =
6213 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6214 assert(!CheckQTN && "Dependent type name canonicalization broken");
6215 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006216 }
6217
6218 DependentTemplateNames.InsertNode(QTN, InsertPos);
6219 return TemplateName(QTN);
6220}
6221
Douglas Gregor71395fa2009-11-04 00:56:37 +00006222/// \brief Retrieve the template name that represents a dependent
6223/// template name such as \c MetaFun::template operator+.
6224TemplateName
6225ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006226 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006227 assert((!NNS || NNS->isDependent()) &&
6228 "Nested name specifier must be dependent");
6229
6230 llvm::FoldingSetNodeID ID;
6231 DependentTemplateName::Profile(ID, NNS, Operator);
6232
6233 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006234 DependentTemplateName *QTN
6235 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006236
6237 if (QTN)
6238 return TemplateName(QTN);
6239
6240 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6241 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006242 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6243 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006244 } else {
6245 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006246 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6247 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006248
6249 DependentTemplateName *CheckQTN
6250 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6251 assert(!CheckQTN && "Dependent template name canonicalization broken");
6252 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006253 }
6254
6255 DependentTemplateNames.InsertNode(QTN, InsertPos);
6256 return TemplateName(QTN);
6257}
6258
Douglas Gregor5590be02011-01-15 06:45:20 +00006259TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006260ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6261 TemplateName replacement) const {
6262 llvm::FoldingSetNodeID ID;
6263 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6264
6265 void *insertPos = 0;
6266 SubstTemplateTemplateParmStorage *subst
6267 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6268
6269 if (!subst) {
6270 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6271 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6272 }
6273
6274 return TemplateName(subst);
6275}
6276
6277TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006278ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6279 const TemplateArgument &ArgPack) const {
6280 ASTContext &Self = const_cast<ASTContext &>(*this);
6281 llvm::FoldingSetNodeID ID;
6282 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6283
6284 void *InsertPos = 0;
6285 SubstTemplateTemplateParmPackStorage *Subst
6286 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6287
6288 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006289 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006290 ArgPack.pack_size(),
6291 ArgPack.pack_begin());
6292 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6293 }
6294
6295 return TemplateName(Subst);
6296}
6297
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006298/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006299/// TargetInfo, produce the corresponding type. The unsigned @p Type
6300/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006301CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006302 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006303 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006304 case TargetInfo::SignedChar: return SignedCharTy;
6305 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006306 case TargetInfo::SignedShort: return ShortTy;
6307 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6308 case TargetInfo::SignedInt: return IntTy;
6309 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6310 case TargetInfo::SignedLong: return LongTy;
6311 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6312 case TargetInfo::SignedLongLong: return LongLongTy;
6313 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6314 }
6315
David Blaikie83d382b2011-09-23 05:06:16 +00006316 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006317}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006318
6319//===----------------------------------------------------------------------===//
6320// Type Predicates.
6321//===----------------------------------------------------------------------===//
6322
Fariborz Jahanian96207692009-02-18 21:49:28 +00006323/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6324/// garbage collection attribute.
6325///
John McCall553d45a2011-01-12 00:34:59 +00006326Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006327 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006328 return Qualifiers::GCNone;
6329
David Blaikiebbafb8a2012-03-11 07:00:24 +00006330 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006331 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6332
6333 // Default behaviour under objective-C's gc is for ObjC pointers
6334 // (or pointers to them) be treated as though they were declared
6335 // as __strong.
6336 if (GCAttrs == Qualifiers::GCNone) {
6337 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6338 return Qualifiers::Strong;
6339 else if (Ty->isPointerType())
6340 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6341 } else {
6342 // It's not valid to set GC attributes on anything that isn't a
6343 // pointer.
6344#ifndef NDEBUG
6345 QualType CT = Ty->getCanonicalTypeInternal();
6346 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6347 CT = AT->getElementType();
6348 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6349#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006350 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006351 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006352}
6353
Chris Lattner49af6a42008-04-07 06:51:04 +00006354//===----------------------------------------------------------------------===//
6355// Type Compatibility Testing
6356//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006357
Mike Stump11289f42009-09-09 15:08:12 +00006358/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006359/// compatible.
6360static bool areCompatVectorTypes(const VectorType *LHS,
6361 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006362 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006363 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006364 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006365}
6366
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006367bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6368 QualType SecondVec) {
6369 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6370 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6371
6372 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6373 return true;
6374
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006375 // Treat Neon vector types and most AltiVec vector types as if they are the
6376 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006377 const VectorType *First = FirstVec->getAs<VectorType>();
6378 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006379 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006380 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006381 First->getVectorKind() != VectorType::AltiVecPixel &&
6382 First->getVectorKind() != VectorType::AltiVecBool &&
6383 Second->getVectorKind() != VectorType::AltiVecPixel &&
6384 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006385 return true;
6386
6387 return false;
6388}
6389
Steve Naroff8e6aee52009-07-23 01:01:38 +00006390//===----------------------------------------------------------------------===//
6391// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6392//===----------------------------------------------------------------------===//
6393
6394/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6395/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006396bool
6397ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6398 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006399 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006400 return true;
6401 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6402 E = rProto->protocol_end(); PI != E; ++PI)
6403 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6404 return true;
6405 return false;
6406}
6407
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006408/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6409/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006410bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6411 QualType rhs) {
6412 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6413 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6414 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6415
6416 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6417 E = lhsQID->qual_end(); I != E; ++I) {
6418 bool match = false;
6419 ObjCProtocolDecl *lhsProto = *I;
6420 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6421 E = rhsOPT->qual_end(); J != E; ++J) {
6422 ObjCProtocolDecl *rhsProto = *J;
6423 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6424 match = true;
6425 break;
6426 }
6427 }
6428 if (!match)
6429 return false;
6430 }
6431 return true;
6432}
6433
Steve Naroff8e6aee52009-07-23 01:01:38 +00006434/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6435/// ObjCQualifiedIDType.
6436bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6437 bool compare) {
6438 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006439 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006440 lhs->isObjCIdType() || lhs->isObjCClassType())
6441 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006442 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006443 rhs->isObjCIdType() || rhs->isObjCClassType())
6444 return true;
6445
6446 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006447 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006448
Steve Naroff8e6aee52009-07-23 01:01:38 +00006449 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006450
Steve Naroff8e6aee52009-07-23 01:01:38 +00006451 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006452 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006453 // make sure we check the class hierarchy.
6454 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6455 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6456 E = lhsQID->qual_end(); I != E; ++I) {
6457 // when comparing an id<P> on lhs with a static type on rhs,
6458 // see if static class implements all of id's protocols, directly or
6459 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006460 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006461 return false;
6462 }
6463 }
6464 // If there are no qualifiers and no interface, we have an 'id'.
6465 return true;
6466 }
Mike Stump11289f42009-09-09 15:08:12 +00006467 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006468 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6469 E = lhsQID->qual_end(); I != E; ++I) {
6470 ObjCProtocolDecl *lhsProto = *I;
6471 bool match = false;
6472
6473 // when comparing an id<P> on lhs with a static type on rhs,
6474 // see if static class implements all of id's protocols, directly or
6475 // through its super class and categories.
6476 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6477 E = rhsOPT->qual_end(); J != E; ++J) {
6478 ObjCProtocolDecl *rhsProto = *J;
6479 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6480 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6481 match = true;
6482 break;
6483 }
6484 }
Mike Stump11289f42009-09-09 15:08:12 +00006485 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006486 // make sure we check the class hierarchy.
6487 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6488 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6489 E = lhsQID->qual_end(); I != E; ++I) {
6490 // when comparing an id<P> on lhs with a static type on rhs,
6491 // see if static class implements all of id's protocols, directly or
6492 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006493 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006494 match = true;
6495 break;
6496 }
6497 }
6498 }
6499 if (!match)
6500 return false;
6501 }
Mike Stump11289f42009-09-09 15:08:12 +00006502
Steve Naroff8e6aee52009-07-23 01:01:38 +00006503 return true;
6504 }
Mike Stump11289f42009-09-09 15:08:12 +00006505
Steve Naroff8e6aee52009-07-23 01:01:38 +00006506 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6507 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6508
Mike Stump11289f42009-09-09 15:08:12 +00006509 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006510 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006511 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006512 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6513 E = lhsOPT->qual_end(); I != E; ++I) {
6514 ObjCProtocolDecl *lhsProto = *I;
6515 bool match = false;
6516
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006517 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006518 // see if static class implements all of id's protocols, directly or
6519 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006520 // First, lhs protocols in the qualifier list must be found, direct
6521 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006522 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6523 E = rhsQID->qual_end(); J != E; ++J) {
6524 ObjCProtocolDecl *rhsProto = *J;
6525 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6526 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6527 match = true;
6528 break;
6529 }
6530 }
6531 if (!match)
6532 return false;
6533 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006534
6535 // Static class's protocols, or its super class or category protocols
6536 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6537 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6538 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6539 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6540 // This is rather dubious but matches gcc's behavior. If lhs has
6541 // no type qualifier and its class has no static protocol(s)
6542 // assume that it is mismatch.
6543 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6544 return false;
6545 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6546 LHSInheritedProtocols.begin(),
6547 E = LHSInheritedProtocols.end(); I != E; ++I) {
6548 bool match = false;
6549 ObjCProtocolDecl *lhsProto = (*I);
6550 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6551 E = rhsQID->qual_end(); J != E; ++J) {
6552 ObjCProtocolDecl *rhsProto = *J;
6553 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6554 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6555 match = true;
6556 break;
6557 }
6558 }
6559 if (!match)
6560 return false;
6561 }
6562 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006563 return true;
6564 }
6565 return false;
6566}
6567
Eli Friedman47f77112008-08-22 00:56:42 +00006568/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006569/// compatible for assignment from RHS to LHS. This handles validation of any
6570/// protocol qualifiers on the LHS or RHS.
6571///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006572bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6573 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006574 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6575 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6576
Steve Naroff1329fa02009-07-15 18:40:39 +00006577 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006578 if (LHS->isObjCUnqualifiedIdOrClass() ||
6579 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006580 return true;
6581
John McCall8b07ec22010-05-15 11:32:37 +00006582 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006583 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6584 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006585 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006586
6587 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6588 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6589 QualType(RHSOPT,0));
6590
John McCall8b07ec22010-05-15 11:32:37 +00006591 // If we have 2 user-defined types, fall into that path.
6592 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006593 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006594
Steve Naroff8e6aee52009-07-23 01:01:38 +00006595 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006596}
6597
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006598/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006599/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006600/// arguments in block literals. When passed as arguments, passing 'A*' where
6601/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6602/// not OK. For the return type, the opposite is not OK.
6603bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6604 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006605 const ObjCObjectPointerType *RHSOPT,
6606 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006607 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006608 return true;
6609
6610 if (LHSOPT->isObjCBuiltinType()) {
6611 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6612 }
6613
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006614 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006615 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6616 QualType(RHSOPT,0),
6617 false);
6618
6619 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6620 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6621 if (LHS && RHS) { // We have 2 user-defined types.
6622 if (LHS != RHS) {
6623 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006624 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006625 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006626 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006627 }
6628 else
6629 return true;
6630 }
6631 return false;
6632}
6633
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006634/// getIntersectionOfProtocols - This routine finds the intersection of set
6635/// of protocols inherited from two distinct objective-c pointer objects.
6636/// It is used to build composite qualifier list of the composite type of
6637/// the conditional expression involving two objective-c pointer objects.
6638static
6639void getIntersectionOfProtocols(ASTContext &Context,
6640 const ObjCObjectPointerType *LHSOPT,
6641 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006642 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006643
John McCall8b07ec22010-05-15 11:32:37 +00006644 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6645 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6646 assert(LHS->getInterface() && "LHS must have an interface base");
6647 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006648
6649 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6650 unsigned LHSNumProtocols = LHS->getNumProtocols();
6651 if (LHSNumProtocols > 0)
6652 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6653 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006654 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006655 Context.CollectInheritedProtocols(LHS->getInterface(),
6656 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006657 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6658 LHSInheritedProtocols.end());
6659 }
6660
6661 unsigned RHSNumProtocols = RHS->getNumProtocols();
6662 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006663 ObjCProtocolDecl **RHSProtocols =
6664 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006665 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6666 if (InheritedProtocolSet.count(RHSProtocols[i]))
6667 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006668 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006669 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006670 Context.CollectInheritedProtocols(RHS->getInterface(),
6671 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006672 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6673 RHSInheritedProtocols.begin(),
6674 E = RHSInheritedProtocols.end(); I != E; ++I)
6675 if (InheritedProtocolSet.count((*I)))
6676 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006677 }
6678}
6679
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006680/// areCommonBaseCompatible - Returns common base class of the two classes if
6681/// one found. Note that this is O'2 algorithm. But it will be called as the
6682/// last type comparison in a ?-exp of ObjC pointer types before a
6683/// warning is issued. So, its invokation is extremely rare.
6684QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006685 const ObjCObjectPointerType *Lptr,
6686 const ObjCObjectPointerType *Rptr) {
6687 const ObjCObjectType *LHS = Lptr->getObjectType();
6688 const ObjCObjectType *RHS = Rptr->getObjectType();
6689 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6690 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006691 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006692 return QualType();
6693
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006694 do {
John McCall8b07ec22010-05-15 11:32:37 +00006695 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006696 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006697 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006698 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6699
6700 QualType Result = QualType(LHS, 0);
6701 if (!Protocols.empty())
6702 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6703 Result = getObjCObjectPointerType(Result);
6704 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006705 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006706 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006707
6708 return QualType();
6709}
6710
John McCall8b07ec22010-05-15 11:32:37 +00006711bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6712 const ObjCObjectType *RHS) {
6713 assert(LHS->getInterface() && "LHS is not an interface type");
6714 assert(RHS->getInterface() && "RHS is not an interface type");
6715
Chris Lattner49af6a42008-04-07 06:51:04 +00006716 // Verify that the base decls are compatible: the RHS must be a subclass of
6717 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006718 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006719 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006720
Chris Lattner49af6a42008-04-07 06:51:04 +00006721 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6722 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006723 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006724 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006725
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006726 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6727 // more detailed analysis is required.
6728 if (RHS->getNumProtocols() == 0) {
6729 // OK, if LHS is a superclass of RHS *and*
6730 // this superclass is assignment compatible with LHS.
6731 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006732 bool IsSuperClass =
6733 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6734 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006735 // OK if conversion of LHS to SuperClass results in narrowing of types
6736 // ; i.e., SuperClass may implement at least one of the protocols
6737 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6738 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6739 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006740 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006741 // If super class has no protocols, it is not a match.
6742 if (SuperClassInheritedProtocols.empty())
6743 return false;
6744
6745 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6746 LHSPE = LHS->qual_end();
6747 LHSPI != LHSPE; LHSPI++) {
6748 bool SuperImplementsProtocol = false;
6749 ObjCProtocolDecl *LHSProto = (*LHSPI);
6750
6751 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6752 SuperClassInheritedProtocols.begin(),
6753 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6754 ObjCProtocolDecl *SuperClassProto = (*I);
6755 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6756 SuperImplementsProtocol = true;
6757 break;
6758 }
6759 }
6760 if (!SuperImplementsProtocol)
6761 return false;
6762 }
6763 return true;
6764 }
6765 return false;
6766 }
Mike Stump11289f42009-09-09 15:08:12 +00006767
John McCall8b07ec22010-05-15 11:32:37 +00006768 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6769 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006770 LHSPI != LHSPE; LHSPI++) {
6771 bool RHSImplementsProtocol = false;
6772
6773 // If the RHS doesn't implement the protocol on the left, the types
6774 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006775 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6776 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006777 RHSPI != RHSPE; RHSPI++) {
6778 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006779 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006780 break;
6781 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006782 }
6783 // FIXME: For better diagnostics, consider passing back the protocol name.
6784 if (!RHSImplementsProtocol)
6785 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006786 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006787 // The RHS implements all protocols listed on the LHS.
6788 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006789}
6790
Steve Naroffb7605152009-02-12 17:52:19 +00006791bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6792 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006793 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6794 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006795
Steve Naroff7cae42b2009-07-10 23:34:53 +00006796 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006797 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006798
6799 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6800 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006801}
6802
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006803bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6804 return canAssignObjCInterfaces(
6805 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6806 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6807}
6808
Mike Stump11289f42009-09-09 15:08:12 +00006809/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006810/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006811/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006812/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006813bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6814 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006815 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006816 return hasSameType(LHS, RHS);
6817
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006818 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006819}
6820
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006821bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006822 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006823}
6824
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006825bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6826 return !mergeTypes(LHS, RHS, true).isNull();
6827}
6828
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006829/// mergeTransparentUnionType - if T is a transparent union type and a member
6830/// of T is compatible with SubType, return the merged type, else return
6831/// QualType()
6832QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6833 bool OfBlockPointer,
6834 bool Unqualified) {
6835 if (const RecordType *UT = T->getAsUnionType()) {
6836 RecordDecl *UD = UT->getDecl();
6837 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006838 for (const auto *I : UD->fields()) {
6839 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006840 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6841 if (!MT.isNull())
6842 return MT;
6843 }
6844 }
6845 }
6846
6847 return QualType();
6848}
6849
Alp Toker9cacbab2014-01-20 20:26:09 +00006850/// mergeFunctionParameterTypes - merge two types which appear as function
6851/// parameter types
6852QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6853 bool OfBlockPointer,
6854 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006855 // GNU extension: two types are compatible if they appear as a function
6856 // argument, one of the types is a transparent union type and the other
6857 // type is compatible with a union member
6858 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6859 Unqualified);
6860 if (!lmerge.isNull())
6861 return lmerge;
6862
6863 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6864 Unqualified);
6865 if (!rmerge.isNull())
6866 return rmerge;
6867
6868 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6869}
6870
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006871QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006872 bool OfBlockPointer,
6873 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006874 const FunctionType *lbase = lhs->getAs<FunctionType>();
6875 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006876 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6877 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006878 bool allLTypes = true;
6879 bool allRTypes = true;
6880
6881 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006882 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006883 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006884 QualType RHS = rbase->getReturnType();
6885 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006886 bool UnqualifiedResult = Unqualified;
6887 if (!UnqualifiedResult)
6888 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006889 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006890 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006891 else
Alp Toker314cc812014-01-25 16:55:45 +00006892 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006893 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006894 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006895
6896 if (Unqualified)
6897 retType = retType.getUnqualifiedType();
6898
Alp Toker314cc812014-01-25 16:55:45 +00006899 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6900 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006901 if (Unqualified) {
6902 LRetType = LRetType.getUnqualifiedType();
6903 RRetType = RRetType.getUnqualifiedType();
6904 }
6905
6906 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006907 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006908 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006909 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006910
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006911 // FIXME: double check this
6912 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6913 // rbase->getRegParmAttr() != 0 &&
6914 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006915 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6916 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006917
Douglas Gregor8c940862010-01-18 17:14:39 +00006918 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006919 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006920 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006921
John McCall8c6b56f2010-12-15 01:06:38 +00006922 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006923 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6924 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006925 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6926 return QualType();
6927
John McCall31168b02011-06-15 23:02:42 +00006928 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6929 return QualType();
6930
John McCall8c6b56f2010-12-15 01:06:38 +00006931 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6932 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006933
Rafael Espindola8778c282012-11-29 16:09:03 +00006934 if (lbaseInfo.getNoReturn() != NoReturn)
6935 allLTypes = false;
6936 if (rbaseInfo.getNoReturn() != NoReturn)
6937 allRTypes = false;
6938
John McCall31168b02011-06-15 23:02:42 +00006939 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006940
Eli Friedman47f77112008-08-22 00:56:42 +00006941 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006942 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6943 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006944 // Compatible functions must have the same number of parameters
6945 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006946 return QualType();
6947
6948 // Variadic and non-variadic functions aren't compatible
6949 if (lproto->isVariadic() != rproto->isVariadic())
6950 return QualType();
6951
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006952 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6953 return QualType();
6954
Fariborz Jahanian97676972011-09-28 21:52:05 +00006955 if (LangOpts.ObjCAutoRefCount &&
6956 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6957 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006958
6959 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006960 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006961 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6962 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6963 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6964 QualType paramType = mergeFunctionParameterTypes(
6965 lParamType, rParamType, OfBlockPointer, Unqualified);
6966 if (paramType.isNull())
6967 return QualType();
6968
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006969 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006970 paramType = paramType.getUnqualifiedType();
6971
6972 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006973 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006974 lParamType = lParamType.getUnqualifiedType();
6975 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006976 }
Alp Toker601b22c2014-01-21 23:35:24 +00006977
6978 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006979 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006980 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006981 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006982 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006983
Eli Friedman47f77112008-08-22 00:56:42 +00006984 if (allLTypes) return lhs;
6985 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006986
6987 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6988 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006989 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006990 }
6991
6992 if (lproto) allRTypes = false;
6993 if (rproto) allLTypes = false;
6994
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006995 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006996 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006997 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006998 if (proto->isVariadic()) return QualType();
6999 // Check that the types are compatible with the types that
7000 // would result from default argument promotions (C99 6.7.5.3p15).
7001 // The only types actually affected are promotable integer
7002 // types and floats, which would be passed as a different
7003 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007004 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7005 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007006
Eli Friedman448ce402012-08-30 00:44:15 +00007007 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007008 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007009 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7010 paramTy = Enum->getDecl()->getIntegerType();
7011 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007012 return QualType();
7013 }
Alp Toker601b22c2014-01-21 23:35:24 +00007014
7015 if (paramTy->isPromotableIntegerType() ||
7016 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007017 return QualType();
7018 }
7019
7020 if (allLTypes) return lhs;
7021 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007022
7023 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7024 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007025 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007026 }
7027
7028 if (allLTypes) return lhs;
7029 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007030 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007031}
7032
John McCall433c2e62013-03-21 00:10:07 +00007033/// Given that we have an enum type and a non-enum type, try to merge them.
7034static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7035 QualType other, bool isBlockReturnType) {
7036 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7037 // a signed integer type, or an unsigned integer type.
7038 // Compatibility is based on the underlying type, not the promotion
7039 // type.
7040 QualType underlyingType = ET->getDecl()->getIntegerType();
7041 if (underlyingType.isNull()) return QualType();
7042 if (Context.hasSameType(underlyingType, other))
7043 return other;
7044
7045 // In block return types, we're more permissive and accept any
7046 // integral type of the same size.
7047 if (isBlockReturnType && other->isIntegerType() &&
7048 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7049 return other;
7050
7051 return QualType();
7052}
7053
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007054QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007055 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007056 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007057 // C++ [expr]: If an expression initially has the type "reference to T", the
7058 // type is adjusted to "T" prior to any further analysis, the expression
7059 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007060 // expression is an lvalue unless the reference is an rvalue reference and
7061 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007062 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7063 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007064
7065 if (Unqualified) {
7066 LHS = LHS.getUnqualifiedType();
7067 RHS = RHS.getUnqualifiedType();
7068 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007069
Eli Friedman47f77112008-08-22 00:56:42 +00007070 QualType LHSCan = getCanonicalType(LHS),
7071 RHSCan = getCanonicalType(RHS);
7072
7073 // If two types are identical, they are compatible.
7074 if (LHSCan == RHSCan)
7075 return LHS;
7076
John McCall8ccfcb52009-09-24 19:53:00 +00007077 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007078 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7079 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007080 if (LQuals != RQuals) {
7081 // If any of these qualifiers are different, we have a type
7082 // mismatch.
7083 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007084 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7085 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007086 return QualType();
7087
7088 // Exactly one GC qualifier difference is allowed: __strong is
7089 // okay if the other type has no GC qualifier but is an Objective
7090 // C object pointer (i.e. implicitly strong by default). We fix
7091 // this by pretending that the unqualified type was actually
7092 // qualified __strong.
7093 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7094 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7095 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7096
7097 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7098 return QualType();
7099
7100 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7101 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7102 }
7103 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7104 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7105 }
Eli Friedman47f77112008-08-22 00:56:42 +00007106 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007107 }
7108
7109 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007110
Eli Friedmandcca6332009-06-01 01:22:52 +00007111 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7112 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007113
Chris Lattnerfd652912008-01-14 05:45:46 +00007114 // We want to consider the two function types to be the same for these
7115 // comparisons, just force one to the other.
7116 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7117 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007118
7119 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007120 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7121 LHSClass = Type::ConstantArray;
7122 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7123 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007124
John McCall8b07ec22010-05-15 11:32:37 +00007125 // ObjCInterfaces are just specialized ObjCObjects.
7126 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7127 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7128
Nate Begemance4d7fc2008-04-18 23:10:10 +00007129 // Canonicalize ExtVector -> Vector.
7130 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7131 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007132
Chris Lattner95554662008-04-07 05:43:21 +00007133 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007134 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007135 // Note that we only have special rules for turning block enum
7136 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007137 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007138 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007139 }
John McCall9dd450b2009-09-21 23:43:11 +00007140 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007141 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007142 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007143 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007144 if (OfBlockPointer && !BlockReturnType) {
7145 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7146 return LHS;
7147 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7148 return RHS;
7149 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007150
Eli Friedman47f77112008-08-22 00:56:42 +00007151 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007152 }
Eli Friedman47f77112008-08-22 00:56:42 +00007153
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007154 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007155 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007156#define TYPE(Class, Base)
7157#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007158#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007159#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7160#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7161#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007162 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007163
Richard Smith27d807c2013-04-30 13:56:41 +00007164 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007165 case Type::LValueReference:
7166 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007167 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007168 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007169
John McCall8b07ec22010-05-15 11:32:37 +00007170 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007171 case Type::IncompleteArray:
7172 case Type::VariableArray:
7173 case Type::FunctionProto:
7174 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007175 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007176
Chris Lattnerfd652912008-01-14 05:45:46 +00007177 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007178 {
7179 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007180 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7181 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007182 if (Unqualified) {
7183 LHSPointee = LHSPointee.getUnqualifiedType();
7184 RHSPointee = RHSPointee.getUnqualifiedType();
7185 }
7186 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7187 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007188 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007189 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007190 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007191 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007192 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007193 return getPointerType(ResultType);
7194 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007195 case Type::BlockPointer:
7196 {
7197 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007198 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7199 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007200 if (Unqualified) {
7201 LHSPointee = LHSPointee.getUnqualifiedType();
7202 RHSPointee = RHSPointee.getUnqualifiedType();
7203 }
7204 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7205 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007206 if (ResultType.isNull()) return QualType();
7207 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7208 return LHS;
7209 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7210 return RHS;
7211 return getBlockPointerType(ResultType);
7212 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007213 case Type::Atomic:
7214 {
7215 // Merge two pointer types, while trying to preserve typedef info
7216 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7217 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7218 if (Unqualified) {
7219 LHSValue = LHSValue.getUnqualifiedType();
7220 RHSValue = RHSValue.getUnqualifiedType();
7221 }
7222 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7223 Unqualified);
7224 if (ResultType.isNull()) return QualType();
7225 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7226 return LHS;
7227 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7228 return RHS;
7229 return getAtomicType(ResultType);
7230 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007231 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007232 {
7233 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7234 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7235 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7236 return QualType();
7237
7238 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7239 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007240 if (Unqualified) {
7241 LHSElem = LHSElem.getUnqualifiedType();
7242 RHSElem = RHSElem.getUnqualifiedType();
7243 }
7244
7245 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007246 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007247 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7248 return LHS;
7249 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7250 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007251 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7252 ArrayType::ArraySizeModifier(), 0);
7253 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7254 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007255 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7256 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007257 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7258 return LHS;
7259 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7260 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007261 if (LVAT) {
7262 // FIXME: This isn't correct! But tricky to implement because
7263 // the array's size has to be the size of LHS, but the type
7264 // has to be different.
7265 return LHS;
7266 }
7267 if (RVAT) {
7268 // FIXME: This isn't correct! But tricky to implement because
7269 // the array's size has to be the size of RHS, but the type
7270 // has to be different.
7271 return RHS;
7272 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007273 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7274 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007275 return getIncompleteArrayType(ResultType,
7276 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007277 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007278 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007279 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007280 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007281 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007282 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007283 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007284 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007285 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007286 case Type::Complex:
7287 // Distinct complex types are incompatible.
7288 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007289 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007290 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007291 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7292 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007293 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007294 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007295 case Type::ObjCObject: {
7296 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007297 // FIXME: This should be type compatibility, e.g. whether
7298 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007299 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7300 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7301 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007302 return LHS;
7303
Eli Friedman47f77112008-08-22 00:56:42 +00007304 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007305 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007306 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007307 if (OfBlockPointer) {
7308 if (canAssignObjCInterfacesInBlockPointer(
7309 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007310 RHS->getAs<ObjCObjectPointerType>(),
7311 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007312 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007313 return QualType();
7314 }
John McCall9dd450b2009-09-21 23:43:11 +00007315 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7316 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007317 return LHS;
7318
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007319 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007320 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007321 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007322
David Blaikie8a40f702012-01-17 06:56:22 +00007323 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007324}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007325
Fariborz Jahanian97676972011-09-28 21:52:05 +00007326bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7327 const FunctionProtoType *FromFunctionType,
7328 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007329 if (FromFunctionType->hasAnyConsumedParams() !=
7330 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007331 return false;
7332 FunctionProtoType::ExtProtoInfo FromEPI =
7333 FromFunctionType->getExtProtoInfo();
7334 FunctionProtoType::ExtProtoInfo ToEPI =
7335 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007336 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007337 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7338 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007339 return false;
7340 }
7341 return true;
7342}
7343
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007344/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7345/// 'RHS' attributes and returns the merged version; including for function
7346/// return types.
7347QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7348 QualType LHSCan = getCanonicalType(LHS),
7349 RHSCan = getCanonicalType(RHS);
7350 // If two types are identical, they are compatible.
7351 if (LHSCan == RHSCan)
7352 return LHS;
7353 if (RHSCan->isFunctionType()) {
7354 if (!LHSCan->isFunctionType())
7355 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007356 QualType OldReturnType =
7357 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007358 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007359 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007360 QualType ResReturnType =
7361 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7362 if (ResReturnType.isNull())
7363 return QualType();
7364 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7365 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7366 // In either case, use OldReturnType to build the new function type.
7367 const FunctionType *F = LHS->getAs<FunctionType>();
7368 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007369 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7370 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007371 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007372 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007373 return ResultType;
7374 }
7375 }
7376 return QualType();
7377 }
7378
7379 // If the qualifiers are different, the types can still be merged.
7380 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7381 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7382 if (LQuals != RQuals) {
7383 // If any of these qualifiers are different, we have a type mismatch.
7384 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7385 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7386 return QualType();
7387
7388 // Exactly one GC qualifier difference is allowed: __strong is
7389 // okay if the other type has no GC qualifier but is an Objective
7390 // C object pointer (i.e. implicitly strong by default). We fix
7391 // this by pretending that the unqualified type was actually
7392 // qualified __strong.
7393 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7394 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7395 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7396
7397 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7398 return QualType();
7399
7400 if (GC_L == Qualifiers::Strong)
7401 return LHS;
7402 if (GC_R == Qualifiers::Strong)
7403 return RHS;
7404 return QualType();
7405 }
7406
7407 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7408 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7409 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7410 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7411 if (ResQT == LHSBaseQT)
7412 return LHS;
7413 if (ResQT == RHSBaseQT)
7414 return RHS;
7415 }
7416 return QualType();
7417}
7418
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007419//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007420// Integer Predicates
7421//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007422
Jay Foad39c79802011-01-12 09:06:06 +00007423unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007424 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007425 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007426 if (T->isBooleanType())
7427 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007428 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007429 return (unsigned)getTypeSize(T);
7430}
7431
Abramo Bagnara13640492012-09-09 10:21:24 +00007432QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007433 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007434
7435 // Turn <4 x signed int> -> <4 x unsigned int>
7436 if (const VectorType *VTy = T->getAs<VectorType>())
7437 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007438 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007439
7440 // For enums, we return the unsigned version of the base type.
7441 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007442 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007443
7444 const BuiltinType *BTy = T->getAs<BuiltinType>();
7445 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007446 switch (BTy->getKind()) {
7447 case BuiltinType::Char_S:
7448 case BuiltinType::SChar:
7449 return UnsignedCharTy;
7450 case BuiltinType::Short:
7451 return UnsignedShortTy;
7452 case BuiltinType::Int:
7453 return UnsignedIntTy;
7454 case BuiltinType::Long:
7455 return UnsignedLongTy;
7456 case BuiltinType::LongLong:
7457 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007458 case BuiltinType::Int128:
7459 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007460 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007461 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007462 }
7463}
7464
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007465ASTMutationListener::~ASTMutationListener() { }
7466
Richard Smith1fa5d642013-05-11 05:45:24 +00007467void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7468 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007469
7470//===----------------------------------------------------------------------===//
7471// Builtin Type Computation
7472//===----------------------------------------------------------------------===//
7473
7474/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007475/// pointer over the consumed characters. This returns the resultant type. If
7476/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7477/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7478/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007479///
7480/// RequiresICE is filled in on return to indicate whether the value is required
7481/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007482static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007483 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007484 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007485 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007486 // Modifiers.
7487 int HowLong = 0;
7488 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007489 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007490
Chris Lattnerdc226c22010-10-01 22:42:38 +00007491 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007492 bool Done = false;
7493 while (!Done) {
7494 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007495 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007496 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007497 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007498 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007499 case 'S':
7500 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7501 assert(!Signed && "Can't use 'S' modifier multiple times!");
7502 Signed = true;
7503 break;
7504 case 'U':
7505 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7506 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7507 Unsigned = true;
7508 break;
7509 case 'L':
7510 assert(HowLong <= 2 && "Can't have LLLL modifier");
7511 ++HowLong;
7512 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007513 case 'W':
7514 // This modifier represents int64 type.
7515 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7516 switch (Context.getTargetInfo().getInt64Type()) {
7517 default:
7518 llvm_unreachable("Unexpected integer type");
7519 case TargetInfo::SignedLong:
7520 HowLong = 1;
7521 break;
7522 case TargetInfo::SignedLongLong:
7523 HowLong = 2;
7524 break;
7525 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007526 }
7527 }
7528
7529 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007530
Chris Lattnerecd79c62009-06-14 00:45:47 +00007531 // Read the base type.
7532 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007533 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007534 case 'v':
7535 assert(HowLong == 0 && !Signed && !Unsigned &&
7536 "Bad modifiers used with 'v'!");
7537 Type = Context.VoidTy;
7538 break;
Jack Carter24bef982013-08-15 15:16:57 +00007539 case 'h':
7540 assert(HowLong == 0 && !Signed && !Unsigned &&
7541 "Bad modifiers used with 'f'!");
7542 Type = Context.HalfTy;
7543 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007544 case 'f':
7545 assert(HowLong == 0 && !Signed && !Unsigned &&
7546 "Bad modifiers used with 'f'!");
7547 Type = Context.FloatTy;
7548 break;
7549 case 'd':
7550 assert(HowLong < 2 && !Signed && !Unsigned &&
7551 "Bad modifiers used with 'd'!");
7552 if (HowLong)
7553 Type = Context.LongDoubleTy;
7554 else
7555 Type = Context.DoubleTy;
7556 break;
7557 case 's':
7558 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7559 if (Unsigned)
7560 Type = Context.UnsignedShortTy;
7561 else
7562 Type = Context.ShortTy;
7563 break;
7564 case 'i':
7565 if (HowLong == 3)
7566 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7567 else if (HowLong == 2)
7568 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7569 else if (HowLong == 1)
7570 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7571 else
7572 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7573 break;
7574 case 'c':
7575 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7576 if (Signed)
7577 Type = Context.SignedCharTy;
7578 else if (Unsigned)
7579 Type = Context.UnsignedCharTy;
7580 else
7581 Type = Context.CharTy;
7582 break;
7583 case 'b': // boolean
7584 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7585 Type = Context.BoolTy;
7586 break;
7587 case 'z': // size_t.
7588 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7589 Type = Context.getSizeType();
7590 break;
7591 case 'F':
7592 Type = Context.getCFConstantStringType();
7593 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007594 case 'G':
7595 Type = Context.getObjCIdType();
7596 break;
7597 case 'H':
7598 Type = Context.getObjCSelType();
7599 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007600 case 'M':
7601 Type = Context.getObjCSuperType();
7602 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007603 case 'a':
7604 Type = Context.getBuiltinVaListType();
7605 assert(!Type.isNull() && "builtin va list type not initialized!");
7606 break;
7607 case 'A':
7608 // This is a "reference" to a va_list; however, what exactly
7609 // this means depends on how va_list is defined. There are two
7610 // different kinds of va_list: ones passed by value, and ones
7611 // passed by reference. An example of a by-value va_list is
7612 // x86, where va_list is a char*. An example of by-ref va_list
7613 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7614 // we want this argument to be a char*&; for x86-64, we want
7615 // it to be a __va_list_tag*.
7616 Type = Context.getBuiltinVaListType();
7617 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007618 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007619 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007620 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007621 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007622 break;
7623 case 'V': {
7624 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007625 unsigned NumElements = strtoul(Str, &End, 10);
7626 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007627 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007628
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007629 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7630 RequiresICE, false);
7631 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007632
7633 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007634 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007635 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007636 break;
7637 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007638 case 'E': {
7639 char *End;
7640
7641 unsigned NumElements = strtoul(Str, &End, 10);
7642 assert(End != Str && "Missing vector size");
7643
7644 Str = End;
7645
7646 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7647 false);
7648 Type = Context.getExtVectorType(ElementType, NumElements);
7649 break;
7650 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007651 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007652 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7653 false);
7654 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007655 Type = Context.getComplexType(ElementType);
7656 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007657 }
7658 case 'Y' : {
7659 Type = Context.getPointerDiffType();
7660 break;
7661 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007662 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007663 Type = Context.getFILEType();
7664 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007665 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007666 return QualType();
7667 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007668 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007669 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007670 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007671 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007672 else
7673 Type = Context.getjmp_bufType();
7674
Mike Stump2adb4da2009-07-28 23:47:15 +00007675 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007676 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007677 return QualType();
7678 }
7679 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007680 case 'K':
7681 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7682 Type = Context.getucontext_tType();
7683
7684 if (Type.isNull()) {
7685 Error = ASTContext::GE_Missing_ucontext;
7686 return QualType();
7687 }
7688 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007689 case 'p':
7690 Type = Context.getProcessIDType();
7691 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007692 }
Mike Stump11289f42009-09-09 15:08:12 +00007693
Chris Lattnerdc226c22010-10-01 22:42:38 +00007694 // If there are modifiers and if we're allowed to parse them, go for it.
7695 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007696 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007697 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007698 default: Done = true; --Str; break;
7699 case '*':
7700 case '&': {
7701 // Both pointers and references can have their pointee types
7702 // qualified with an address space.
7703 char *End;
7704 unsigned AddrSpace = strtoul(Str, &End, 10);
7705 if (End != Str && AddrSpace != 0) {
7706 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7707 Str = End;
7708 }
7709 if (c == '*')
7710 Type = Context.getPointerType(Type);
7711 else
7712 Type = Context.getLValueReferenceType(Type);
7713 break;
7714 }
7715 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7716 case 'C':
7717 Type = Type.withConst();
7718 break;
7719 case 'D':
7720 Type = Context.getVolatileType(Type);
7721 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007722 case 'R':
7723 Type = Type.withRestrict();
7724 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007725 }
7726 }
Chris Lattner84733392010-10-01 07:13:18 +00007727
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007728 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007729 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007730
Chris Lattnerecd79c62009-06-14 00:45:47 +00007731 return Type;
7732}
7733
7734/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007735QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007736 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007737 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007738 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007739
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007740 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007741
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007742 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007743 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007744 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7745 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007746 if (Error != GE_None)
7747 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007748
7749 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7750
Chris Lattnerecd79c62009-06-14 00:45:47 +00007751 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007752 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007753 if (Error != GE_None)
7754 return QualType();
7755
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007756 // If this argument is required to be an IntegerConstantExpression and the
7757 // caller cares, fill in the bitmask we return.
7758 if (RequiresICE && IntegerConstantArgs)
7759 *IntegerConstantArgs |= 1 << ArgTypes.size();
7760
Chris Lattnerecd79c62009-06-14 00:45:47 +00007761 // Do array -> pointer decay. The builtin should use the decayed type.
7762 if (Ty->isArrayType())
7763 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007764
Chris Lattnerecd79c62009-06-14 00:45:47 +00007765 ArgTypes.push_back(Ty);
7766 }
7767
7768 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7769 "'.' should only occur at end of builtin type list!");
7770
Reid Kleckner78af0702013-08-27 23:08:25 +00007771 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007772 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7773
7774 bool Variadic = (TypeStr[0] == '.');
7775
7776 // We really shouldn't be making a no-proto type here, especially in C++.
7777 if (ArgTypes.empty() && Variadic)
7778 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007779
John McCalldb40c7f2010-12-14 08:05:40 +00007780 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007781 EPI.ExtInfo = EI;
7782 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007783
Jordan Rose5c382722013-03-08 21:51:21 +00007784 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007785}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007786
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007787GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007788 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007789 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007790
Rafael Espindola3ae00052013-05-13 00:12:11 +00007791 GVALinkage External = GVA_StrongExternal;
7792 switch (FD->getTemplateSpecializationKind()) {
7793 case TSK_Undeclared:
7794 case TSK_ExplicitSpecialization:
7795 External = GVA_StrongExternal;
7796 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007797
Rafael Espindola3ae00052013-05-13 00:12:11 +00007798 case TSK_ExplicitInstantiationDefinition:
7799 return GVA_ExplicitTemplateInstantiation;
7800
7801 case TSK_ExplicitInstantiationDeclaration:
7802 case TSK_ImplicitInstantiation:
7803 External = GVA_TemplateInstantiation;
7804 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007805 }
7806
7807 if (!FD->isInlined())
7808 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007809
Alp Tokerbfa39342014-01-14 12:51:41 +00007810 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007811 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007812 // GNU or C99 inline semantics. Determine whether this symbol should be
7813 // externally visible.
7814 if (FD->isInlineDefinitionExternallyVisible())
7815 return External;
7816
7817 // C99 inline semantics, where the symbol is not externally visible.
7818 return GVA_C99Inline;
7819 }
7820
7821 // C++0x [temp.explicit]p9:
7822 // [ Note: The intent is that an inline function that is the subject of
7823 // an explicit instantiation declaration will still be implicitly
7824 // instantiated when used so that the body can be considered for
7825 // inlining, but that no out-of-line copy of the inline function would be
7826 // generated in the translation unit. -- end note ]
7827 if (FD->getTemplateSpecializationKind()
7828 == TSK_ExplicitInstantiationDeclaration)
7829 return GVA_C99Inline;
7830
7831 return GVA_CXXInline;
7832}
7833
7834GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007835 if (!VD->isExternallyVisible())
7836 return GVA_Internal;
7837
Richard Smith8809a0c2013-09-27 20:14:12 +00007838 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007839 case TSK_Undeclared:
7840 case TSK_ExplicitSpecialization:
7841 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007842
Rafael Espindola3ae00052013-05-13 00:12:11 +00007843 case TSK_ExplicitInstantiationDeclaration:
7844 llvm_unreachable("Variable should not be instantiated");
7845 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007846
Rafael Espindola3ae00052013-05-13 00:12:11 +00007847 case TSK_ExplicitInstantiationDefinition:
7848 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007849
Rafael Espindola3ae00052013-05-13 00:12:11 +00007850 case TSK_ImplicitInstantiation:
7851 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007852 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007853
7854 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007855}
7856
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007857bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007858 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7859 if (!VD->isFileVarDecl())
7860 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007861 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7862 // We never need to emit an uninstantiated function template.
7863 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7864 return false;
7865 } else
7866 return false;
7867
7868 // If this is a member of a class template, we do not need to emit it.
7869 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007870 return false;
7871
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007872 // Weak references don't produce any output by themselves.
7873 if (D->hasAttr<WeakRefAttr>())
7874 return false;
7875
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007876 // Aliases and used decls are required.
7877 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7878 return true;
7879
7880 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7881 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007882 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007883 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007884
7885 // Constructors and destructors are required.
7886 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7887 return true;
7888
John McCall6bd2a892013-01-25 22:31:03 +00007889 // The key function for a class is required. This rule only comes
7890 // into play when inline functions can be key functions, though.
7891 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7892 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7893 const CXXRecordDecl *RD = MD->getParent();
7894 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7895 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7896 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7897 return true;
7898 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007899 }
7900 }
7901
7902 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7903
7904 // static, static inline, always_inline, and extern inline functions can
7905 // always be deferred. Normal inline functions can be deferred in C99/C++.
7906 // Implicit template instantiations can also be deferred in C++.
7907 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007908 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007909 return false;
7910 return true;
7911 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007912
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007913 const VarDecl *VD = cast<VarDecl>(D);
7914 assert(VD->isFileVarDecl() && "Expected file scoped var");
7915
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007916 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7917 return false;
7918
Richard Smitha0e5e542012-11-12 21:38:00 +00007919 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007920 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007921 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7922 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007923
Richard Smitha0e5e542012-11-12 21:38:00 +00007924 // Variables that have destruction with side-effects are required.
7925 if (VD->getType().isDestructedType())
7926 return true;
7927
7928 // Variables that have initialization with side-effects are required.
7929 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7930 return true;
7931
7932 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007933}
Charles Davis53c59df2010-08-16 03:33:14 +00007934
Reid Kleckner78af0702013-08-27 23:08:25 +00007935CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7936 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007937 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007938 if (IsCXXMethod)
7939 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007940
Reid Kleckner78af0702013-08-27 23:08:25 +00007941 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007942}
7943
Jay Foad39c79802011-01-12 09:06:06 +00007944bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007945 // Pass through to the C++ ABI object
7946 return ABI->isNearlyEmpty(RD);
7947}
7948
Reid Kleckner96f8f932014-02-05 17:27:08 +00007949VTableContextBase *ASTContext::getVTableContext() {
7950 if (!VTContext.get()) {
7951 if (Target->getCXXABI().isMicrosoft())
7952 VTContext.reset(new MicrosoftVTableContext(*this));
7953 else
7954 VTContext.reset(new ItaniumVTableContext(*this));
7955 }
7956 return VTContext.get();
7957}
7958
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007959MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007960 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007961 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007962 case TargetCXXABI::GenericItanium:
7963 case TargetCXXABI::GenericARM:
7964 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007965 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007966 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007967 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007968 }
David Blaikie83d382b2011-09-23 05:06:16 +00007969 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007970}
7971
Charles Davis53c59df2010-08-16 03:33:14 +00007972CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007973
7974size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007975 return ASTRecordLayouts.getMemorySize() +
7976 llvm::capacity_in_bytes(ObjCLayouts) +
7977 llvm::capacity_in_bytes(KeyFunctions) +
7978 llvm::capacity_in_bytes(ObjCImpls) +
7979 llvm::capacity_in_bytes(BlockVarCopyInits) +
7980 llvm::capacity_in_bytes(DeclAttrs) +
7981 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7982 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7983 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7984 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7985 llvm::capacity_in_bytes(OverriddenMethods) +
7986 llvm::capacity_in_bytes(Types) +
7987 llvm::capacity_in_bytes(VariableArrayTypes) +
7988 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007989}
Ted Kremenek540017e2011-10-06 05:00:56 +00007990
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007991/// getIntTypeForBitwidth -
7992/// sets integer QualTy according to specified details:
7993/// bitwidth, signed/unsigned.
7994/// Returns empty type if there is no appropriate target types.
7995QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7996 unsigned Signed) const {
7997 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7998 CanQualType QualTy = getFromTargetType(Ty);
7999 if (!QualTy && DestWidth == 128)
8000 return Signed ? Int128Ty : UnsignedInt128Ty;
8001 return QualTy;
8002}
8003
8004/// getRealTypeForBitwidth -
8005/// sets floating point QualTy according to specified bitwidth.
8006/// Returns empty type if there is no appropriate target types.
8007QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8008 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8009 switch (Ty) {
8010 case TargetInfo::Float:
8011 return FloatTy;
8012 case TargetInfo::Double:
8013 return DoubleTy;
8014 case TargetInfo::LongDouble:
8015 return LongDoubleTy;
8016 case TargetInfo::NoFloat:
8017 return QualType();
8018 }
8019
8020 llvm_unreachable("Unhandled TargetInfo::RealType value");
8021}
8022
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008023void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8024 if (Number > 1)
8025 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008026}
8027
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008028unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8029 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8030 MangleNumbers.find(ND);
8031 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008032}
8033
David Majnemer2206bf52014-03-05 08:57:59 +00008034void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8035 if (Number > 1)
8036 StaticLocalNumbers[VD] = Number;
8037}
8038
8039unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8040 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8041 StaticLocalNumbers.find(VD);
8042 return I != StaticLocalNumbers.end() ? I->second : 1;
8043}
8044
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008045MangleNumberingContext &
8046ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008047 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8048 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8049 if (!MCtx)
8050 MCtx = createMangleNumberingContext();
8051 return *MCtx;
8052}
8053
8054MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8055 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008056}
8057
Ted Kremenek540017e2011-10-06 05:00:56 +00008058void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8059 ParamIndices[D] = index;
8060}
8061
8062unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8063 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8064 assert(I != ParamIndices.end() &&
8065 "ParmIndices lacks entry set by ParmVarDecl");
8066 return I->second;
8067}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008068
Richard Smithe6c01442013-06-05 00:46:14 +00008069APValue *
8070ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8071 bool MayCreate) {
8072 assert(E && E->getStorageDuration() == SD_Static &&
8073 "don't need to cache the computed value for this temporary");
8074 if (MayCreate)
8075 return &MaterializedTemporaryValues[E];
8076
8077 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8078 MaterializedTemporaryValues.find(E);
8079 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8080}
8081
Fariborz Jahanian615de762013-05-28 17:37:39 +00008082bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8083 const llvm::Triple &T = getTargetInfo().getTriple();
8084 if (!T.isOSDarwin())
8085 return false;
8086
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008087 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8088 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8089 return false;
8090
Fariborz Jahanian615de762013-05-28 17:37:39 +00008091 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8092 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8093 uint64_t Size = sizeChars.getQuantity();
8094 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8095 unsigned Align = alignChars.getQuantity();
8096 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8097 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8098}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008099
8100namespace {
8101
8102 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8103 /// parents as defined by the \c RecursiveASTVisitor.
8104 ///
8105 /// Note that the relationship described here is purely in terms of AST
8106 /// traversal - there are other relationships (for example declaration context)
8107 /// in the AST that are better modeled by special matchers.
8108 ///
8109 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8110 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8111
8112 public:
8113 /// \brief Builds and returns the translation unit's parent map.
8114 ///
8115 /// The caller takes ownership of the returned \c ParentMap.
8116 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8117 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8118 Visitor.TraverseDecl(&TU);
8119 return Visitor.Parents;
8120 }
8121
8122 private:
8123 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8124
8125 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8126 }
8127
8128 bool shouldVisitTemplateInstantiations() const {
8129 return true;
8130 }
8131 bool shouldVisitImplicitCode() const {
8132 return true;
8133 }
8134 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8135 // are not triggered during data recursion.
8136 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8137 return false;
8138 }
8139
8140 template <typename T>
8141 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8142 if (Node == NULL)
8143 return true;
8144 if (ParentStack.size() > 0)
8145 // FIXME: Currently we add the same parent multiple times, for example
8146 // when we visit all subexpressions of template instantiations; this is
8147 // suboptimal, bug benign: the only way to visit those is with
8148 // hasAncestor / hasParent, and those do not create new matches.
8149 // The plan is to enable DynTypedNode to be storable in a map or hash
8150 // map. The main problem there is to implement hash functions /
8151 // comparison operators for all types that DynTypedNode supports that
8152 // do not have pointer identity.
8153 (*Parents)[Node].push_back(ParentStack.back());
8154 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8155 bool Result = (this ->* traverse) (Node);
8156 ParentStack.pop_back();
8157 return Result;
8158 }
8159
8160 bool TraverseDecl(Decl *DeclNode) {
8161 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8162 }
8163
8164 bool TraverseStmt(Stmt *StmtNode) {
8165 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8166 }
8167
8168 ASTContext::ParentMap *Parents;
8169 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8170
8171 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8172 };
8173
8174} // end namespace
8175
8176ASTContext::ParentVector
8177ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8178 assert(Node.getMemoizationData() &&
8179 "Invariant broken: only nodes that support memoization may be "
8180 "used in the parent map.");
8181 if (!AllParents) {
8182 // We always need to run over the whole translation unit, as
8183 // hasAncestor can escape any subtree.
8184 AllParents.reset(
8185 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8186 }
8187 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8188 if (I == AllParents->end()) {
8189 return ParentVector();
8190 }
8191 return I->second;
8192}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008193
8194bool
8195ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8196 const ObjCMethodDecl *MethodImpl) {
8197 // No point trying to match an unavailable/deprecated mothod.
8198 if (MethodDecl->hasAttr<UnavailableAttr>()
8199 || MethodDecl->hasAttr<DeprecatedAttr>())
8200 return false;
8201 if (MethodDecl->getObjCDeclQualifier() !=
8202 MethodImpl->getObjCDeclQualifier())
8203 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008204 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008205 return false;
8206
8207 if (MethodDecl->param_size() != MethodImpl->param_size())
8208 return false;
8209
8210 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8211 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8212 EF = MethodDecl->param_end();
8213 IM != EM && IF != EF; ++IM, ++IF) {
8214 const ParmVarDecl *DeclVar = (*IF);
8215 const ParmVarDecl *ImplVar = (*IM);
8216 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8217 return false;
8218 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8219 return false;
8220 }
8221 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8222
8223}