blob: 64cdda1c18bee25642c933168fc0bf33d2bcf6ec [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) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001798 for (const auto *I : OI->ivars())
1799 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001800 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001801 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001802 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001803 Iv= Iv->getNextIvar())
1804 Ivars.push_back(Iv);
1805 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001806}
1807
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001808/// CollectInheritedProtocols - Collect all protocols in current class and
1809/// those inherited by it.
1810void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001811 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001812 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001813 // We can use protocol_iterator here instead of
1814 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001815 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001816 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001817 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001818 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001819 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001820 CollectInheritedProtocols(*P, Protocols);
1821 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001822 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001823
1824 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001825 for (const auto *Cat : OI->visible_categories())
1826 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001827
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001828 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1829 while (SD) {
1830 CollectInheritedProtocols(SD, Protocols);
1831 SD = SD->getSuperClass();
1832 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001833 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001834 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001835 PE = OC->protocol_end(); P != PE; ++P) {
1836 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001837 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001838 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1839 PE = Proto->protocol_end(); P != PE; ++P)
1840 CollectInheritedProtocols(*P, Protocols);
1841 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001842 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001843 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1844 PE = OP->protocol_end(); P != PE; ++P) {
1845 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001846 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001847 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1848 PE = Proto->protocol_end(); P != PE; ++P)
1849 CollectInheritedProtocols(*P, Protocols);
1850 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001851 }
1852}
1853
Jay Foad39c79802011-01-12 09:06:06 +00001854unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001855 unsigned count = 0;
1856 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001857 for (ObjCInterfaceDecl::known_extensions_iterator
1858 Ext = OI->known_extensions_begin(),
1859 ExtEnd = OI->known_extensions_end();
1860 Ext != ExtEnd; ++Ext) {
1861 count += Ext->ivar_size();
1862 }
1863
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001864 // Count ivar defined in this class's implementation. This
1865 // includes synthesized ivars.
1866 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001867 count += ImplDecl->ivar_size();
1868
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001869 return count;
1870}
1871
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001872bool ASTContext::isSentinelNullExpr(const Expr *E) {
1873 if (!E)
1874 return false;
1875
1876 // nullptr_t is always treated as null.
1877 if (E->getType()->isNullPtrType()) return true;
1878
1879 if (E->getType()->isAnyPointerType() &&
1880 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1881 Expr::NPC_ValueDependentIsNull))
1882 return true;
1883
1884 // Unfortunately, __null has type 'int'.
1885 if (isa<GNUNullExpr>(E)) return true;
1886
1887 return false;
1888}
1889
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001890/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1891ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1892 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1893 I = ObjCImpls.find(D);
1894 if (I != ObjCImpls.end())
1895 return cast<ObjCImplementationDecl>(I->second);
1896 return 0;
1897}
1898/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1899ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1900 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1901 I = ObjCImpls.find(D);
1902 if (I != ObjCImpls.end())
1903 return cast<ObjCCategoryImplDecl>(I->second);
1904 return 0;
1905}
1906
1907/// \brief Set the implementation of ObjCInterfaceDecl.
1908void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1909 ObjCImplementationDecl *ImplD) {
1910 assert(IFaceD && ImplD && "Passed null params");
1911 ObjCImpls[IFaceD] = ImplD;
1912}
1913/// \brief Set the implementation of ObjCCategoryDecl.
1914void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1915 ObjCCategoryImplDecl *ImplD) {
1916 assert(CatD && ImplD && "Passed null params");
1917 ObjCImpls[CatD] = ImplD;
1918}
1919
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001920const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1921 const NamedDecl *ND) const {
1922 if (const ObjCInterfaceDecl *ID =
1923 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001924 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001925 if (const ObjCCategoryDecl *CD =
1926 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001927 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001928 if (const ObjCImplDecl *IMD =
1929 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001930 return IMD->getClassInterface();
1931
1932 return 0;
1933}
1934
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001935/// \brief Get the copy initialization expression of VarDecl,or NULL if
1936/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001937Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001938 assert(VD && "Passed null params");
1939 assert(VD->hasAttr<BlocksAttr>() &&
1940 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001941 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001942 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001943 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1944}
1945
1946/// \brief Set the copy inialization expression of a block var decl.
1947void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1948 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001949 assert(VD->hasAttr<BlocksAttr>() &&
1950 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001951 BlockVarCopyInits[VD] = Init;
1952}
1953
John McCallbcd03502009-12-07 02:54:59 +00001954TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001955 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001956 if (!DataSize)
1957 DataSize = TypeLoc::getFullDataSizeForType(T);
1958 else
1959 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001960 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001961
John McCallbcd03502009-12-07 02:54:59 +00001962 TypeSourceInfo *TInfo =
1963 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1964 new (TInfo) TypeSourceInfo(T);
1965 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001966}
1967
John McCallbcd03502009-12-07 02:54:59 +00001968TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001969 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001970 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001971 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001972 return DI;
1973}
1974
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001975const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001976ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001977 return getObjCLayout(D, 0);
1978}
1979
1980const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001981ASTContext::getASTObjCImplementationLayout(
1982 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001983 return getObjCLayout(D->getClassInterface(), D);
1984}
1985
Chris Lattner983a8bb2007-07-13 22:13:22 +00001986//===----------------------------------------------------------------------===//
1987// Type creation/memoization methods
1988//===----------------------------------------------------------------------===//
1989
Jay Foad39c79802011-01-12 09:06:06 +00001990QualType
John McCall33ddac02011-01-19 10:06:00 +00001991ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1992 unsigned fastQuals = quals.getFastQualifiers();
1993 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001994
1995 // Check if we've already instantiated this type.
1996 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001997 ExtQuals::Profile(ID, baseType, quals);
1998 void *insertPos = 0;
1999 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2000 assert(eq->getQualifiers() == quals);
2001 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002002 }
2003
John McCall33ddac02011-01-19 10:06:00 +00002004 // If the base type is not canonical, make the appropriate canonical type.
2005 QualType canon;
2006 if (!baseType->isCanonicalUnqualified()) {
2007 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002008 canonSplit.Quals.addConsistentQualifiers(quals);
2009 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002010
2011 // Re-find the insert position.
2012 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2013 }
2014
2015 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2016 ExtQualNodes.InsertNode(eq, insertPos);
2017 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002018}
2019
Jay Foad39c79802011-01-12 09:06:06 +00002020QualType
2021ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002022 QualType CanT = getCanonicalType(T);
2023 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002024 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002025
John McCall8ccfcb52009-09-24 19:53:00 +00002026 // If we are composing extended qualifiers together, merge together
2027 // into one ExtQuals node.
2028 QualifierCollector Quals;
2029 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002030
John McCall8ccfcb52009-09-24 19:53:00 +00002031 // If this type already has an address space specified, it cannot get
2032 // another one.
2033 assert(!Quals.hasAddressSpace() &&
2034 "Type cannot be in multiple addr spaces!");
2035 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002036
John McCall8ccfcb52009-09-24 19:53:00 +00002037 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002038}
2039
Chris Lattnerd60183d2009-02-18 22:53:11 +00002040QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002041 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002042 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002043 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002044 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002045
John McCall53fa7142010-12-24 02:08:15 +00002046 if (const PointerType *ptr = T->getAs<PointerType>()) {
2047 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002048 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002049 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2050 return getPointerType(ResultType);
2051 }
2052 }
Mike Stump11289f42009-09-09 15:08:12 +00002053
John McCall8ccfcb52009-09-24 19:53:00 +00002054 // If we are composing extended qualifiers together, merge together
2055 // into one ExtQuals node.
2056 QualifierCollector Quals;
2057 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002058
John McCall8ccfcb52009-09-24 19:53:00 +00002059 // If this type already has an ObjCGC specified, it cannot get
2060 // another one.
2061 assert(!Quals.hasObjCGCAttr() &&
2062 "Type cannot have multiple ObjCGCs!");
2063 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002064
John McCall8ccfcb52009-09-24 19:53:00 +00002065 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002066}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002067
John McCall4f5019e2010-12-19 02:44:49 +00002068const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2069 FunctionType::ExtInfo Info) {
2070 if (T->getExtInfo() == Info)
2071 return T;
2072
2073 QualType Result;
2074 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002075 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002076 } else {
2077 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2078 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2079 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002080 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002081 }
2082
2083 return cast<FunctionType>(Result.getTypePtr());
2084}
2085
Richard Smith2a7d4812013-05-04 07:00:32 +00002086void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2087 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002088 FD = FD->getMostRecentDecl();
2089 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002090 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002092 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002093 if (FunctionDecl *Next = FD->getPreviousDecl())
2094 FD = Next;
2095 else
2096 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002097 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002098 if (ASTMutationListener *L = getASTMutationListener())
2099 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002100}
2101
Chris Lattnerc6395932007-06-22 20:56:16 +00002102/// getComplexType - Return the uniqued reference to the type for a complex
2103/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002104QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002105 // Unique pointers, to guarantee there is only one pointer of a particular
2106 // structure.
2107 llvm::FoldingSetNodeID ID;
2108 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002109
Chris Lattnerc6395932007-06-22 20:56:16 +00002110 void *InsertPos = 0;
2111 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2112 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattnerc6395932007-06-22 20:56:16 +00002114 // If the pointee type isn't canonical, this won't be a canonical type either,
2115 // so fill in the canonical type field.
2116 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002117 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002118 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002119
Chris Lattnerc6395932007-06-22 20:56:16 +00002120 // Get the new insert position for the node we care about.
2121 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002122 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002123 }
John McCall90d1c2d2009-09-24 23:30:46 +00002124 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002125 Types.push_back(New);
2126 ComplexTypes.InsertNode(New, InsertPos);
2127 return QualType(New, 0);
2128}
2129
Chris Lattner970e54e2006-11-12 00:37:36 +00002130/// getPointerType - Return the uniqued reference to the type for a pointer to
2131/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002132QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002133 // Unique pointers, to guarantee there is only one pointer of a particular
2134 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002135 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002136 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002137
Chris Lattner67521df2007-01-27 01:29:36 +00002138 void *InsertPos = 0;
2139 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002140 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002141
Chris Lattner7ccecb92006-11-12 08:50:50 +00002142 // If the pointee type isn't canonical, this won't be a canonical type either,
2143 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002144 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002145 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002146 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002147
Bob Wilsonc8541f22013-03-15 17:12:43 +00002148 // Get the new insert position for the node we care about.
2149 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2150 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2151 }
John McCall90d1c2d2009-09-24 23:30:46 +00002152 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002153 Types.push_back(New);
2154 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002155 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002156}
2157
Reid Kleckner0503a872013-12-05 01:23:43 +00002158QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2159 llvm::FoldingSetNodeID ID;
2160 AdjustedType::Profile(ID, Orig, New);
2161 void *InsertPos = 0;
2162 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2163 if (AT)
2164 return QualType(AT, 0);
2165
2166 QualType Canonical = getCanonicalType(New);
2167
2168 // Get the new insert position for the node we care about.
2169 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2170 assert(AT == 0 && "Shouldn't be in the map!");
2171
2172 AT = new (*this, TypeAlignment)
2173 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2174 Types.push_back(AT);
2175 AdjustedTypes.InsertNode(AT, InsertPos);
2176 return QualType(AT, 0);
2177}
2178
Reid Kleckner8a365022013-06-24 17:51:48 +00002179QualType ASTContext::getDecayedType(QualType T) const {
2180 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2181
Reid Kleckner8a365022013-06-24 17:51:48 +00002182 QualType Decayed;
2183
2184 // C99 6.7.5.3p7:
2185 // A declaration of a parameter as "array of type" shall be
2186 // adjusted to "qualified pointer to type", where the type
2187 // qualifiers (if any) are those specified within the [ and ] of
2188 // the array type derivation.
2189 if (T->isArrayType())
2190 Decayed = getArrayDecayedType(T);
2191
2192 // C99 6.7.5.3p8:
2193 // A declaration of a parameter as "function returning type"
2194 // shall be adjusted to "pointer to function returning type", as
2195 // in 6.3.2.1.
2196 if (T->isFunctionType())
2197 Decayed = getPointerType(T);
2198
Reid Kleckner0503a872013-12-05 01:23:43 +00002199 llvm::FoldingSetNodeID ID;
2200 AdjustedType::Profile(ID, T, Decayed);
2201 void *InsertPos = 0;
2202 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2203 if (AT)
2204 return QualType(AT, 0);
2205
Reid Kleckner8a365022013-06-24 17:51:48 +00002206 QualType Canonical = getCanonicalType(Decayed);
2207
2208 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002209 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2210 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002211
Reid Kleckner0503a872013-12-05 01:23:43 +00002212 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2213 Types.push_back(AT);
2214 AdjustedTypes.InsertNode(AT, InsertPos);
2215 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002216}
2217
Mike Stump11289f42009-09-09 15:08:12 +00002218/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002219/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002220QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002221 assert(T->isFunctionType() && "block of function types only");
2222 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002223 // structure.
2224 llvm::FoldingSetNodeID ID;
2225 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002226
Steve Naroffec33ed92008-08-27 16:04:49 +00002227 void *InsertPos = 0;
2228 if (BlockPointerType *PT =
2229 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2230 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002231
2232 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002233 // type either so fill in the canonical type field.
2234 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002235 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002236 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002237
Steve Naroffec33ed92008-08-27 16:04:49 +00002238 // Get the new insert position for the node we care about.
2239 BlockPointerType *NewIP =
2240 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002241 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002242 }
John McCall90d1c2d2009-09-24 23:30:46 +00002243 BlockPointerType *New
2244 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002245 Types.push_back(New);
2246 BlockPointerTypes.InsertNode(New, InsertPos);
2247 return QualType(New, 0);
2248}
2249
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002250/// getLValueReferenceType - Return the uniqued reference to the type for an
2251/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002252QualType
2253ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002254 assert(getCanonicalType(T) != OverloadTy &&
2255 "Unresolved overloaded function type");
2256
Bill Wendling3708c182007-05-27 10:15:43 +00002257 // Unique pointers, to guarantee there is only one pointer of a particular
2258 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002259 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002260 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002261
2262 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002263 if (LValueReferenceType *RT =
2264 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002265 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002266
John McCallfc93cf92009-10-22 22:37:11 +00002267 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2268
Bill Wendling3708c182007-05-27 10:15:43 +00002269 // If the referencee type isn't canonical, this won't be a canonical type
2270 // either, so fill in the canonical type field.
2271 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002272 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2273 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2274 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002275
Bill Wendling3708c182007-05-27 10:15:43 +00002276 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002277 LValueReferenceType *NewIP =
2278 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002279 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002280 }
2281
John McCall90d1c2d2009-09-24 23:30:46 +00002282 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002283 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2284 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002285 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002286 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002287
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002288 return QualType(New, 0);
2289}
2290
2291/// getRValueReferenceType - Return the uniqued reference to the type for an
2292/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002293QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002294 // Unique pointers, to guarantee there is only one pointer of a particular
2295 // structure.
2296 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002297 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002298
2299 void *InsertPos = 0;
2300 if (RValueReferenceType *RT =
2301 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2302 return QualType(RT, 0);
2303
John McCallfc93cf92009-10-22 22:37:11 +00002304 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2305
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002306 // If the referencee type isn't canonical, this won't be a canonical type
2307 // either, so fill in the canonical type field.
2308 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002309 if (InnerRef || !T.isCanonical()) {
2310 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2311 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002312
2313 // Get the new insert position for the node we care about.
2314 RValueReferenceType *NewIP =
2315 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002316 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002317 }
2318
John McCall90d1c2d2009-09-24 23:30:46 +00002319 RValueReferenceType *New
2320 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002321 Types.push_back(New);
2322 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002323 return QualType(New, 0);
2324}
2325
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002326/// getMemberPointerType - Return the uniqued reference to the type for a
2327/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002328QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002329 // Unique pointers, to guarantee there is only one pointer of a particular
2330 // structure.
2331 llvm::FoldingSetNodeID ID;
2332 MemberPointerType::Profile(ID, T, Cls);
2333
2334 void *InsertPos = 0;
2335 if (MemberPointerType *PT =
2336 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2337 return QualType(PT, 0);
2338
2339 // If the pointee or class type isn't canonical, this won't be a canonical
2340 // type either, so fill in the canonical type field.
2341 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002342 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002343 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2344
2345 // Get the new insert position for the node we care about.
2346 MemberPointerType *NewIP =
2347 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002348 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002349 }
John McCall90d1c2d2009-09-24 23:30:46 +00002350 MemberPointerType *New
2351 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002352 Types.push_back(New);
2353 MemberPointerTypes.InsertNode(New, InsertPos);
2354 return QualType(New, 0);
2355}
2356
Mike Stump11289f42009-09-09 15:08:12 +00002357/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002358/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002359QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002360 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002361 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002362 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002363 assert((EltTy->isDependentType() ||
2364 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002365 "Constant array of VLAs is illegal!");
2366
Chris Lattnere2df3f92009-05-13 04:12:56 +00002367 // Convert the array size into a canonical width matching the pointer size for
2368 // the target.
2369 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002370 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002371 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002372
Chris Lattner23b7eb62007-06-15 23:05:46 +00002373 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002374 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002375
Chris Lattner36f8e652007-01-27 08:31:04 +00002376 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002377 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002378 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002379 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002380
John McCall33ddac02011-01-19 10:06:00 +00002381 // If the element type isn't canonical or has qualifiers, this won't
2382 // be a canonical type either, so fill in the canonical type field.
2383 QualType Canon;
2384 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2385 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002386 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002387 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002388 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002389
Chris Lattner36f8e652007-01-27 08:31:04 +00002390 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002391 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002392 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002393 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002394 }
Mike Stump11289f42009-09-09 15:08:12 +00002395
John McCall90d1c2d2009-09-24 23:30:46 +00002396 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002397 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002398 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002399 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002400 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002401}
2402
John McCall06549462011-01-18 08:40:38 +00002403/// getVariableArrayDecayedType - Turns the given type, which may be
2404/// variably-modified, into the corresponding type with all the known
2405/// sizes replaced with [*].
2406QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2407 // Vastly most common case.
2408 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002409
John McCall06549462011-01-18 08:40:38 +00002410 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002411
John McCall06549462011-01-18 08:40:38 +00002412 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002413 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002414 switch (ty->getTypeClass()) {
2415#define TYPE(Class, Base)
2416#define ABSTRACT_TYPE(Class, Base)
2417#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2418#include "clang/AST/TypeNodes.def"
2419 llvm_unreachable("didn't desugar past all non-canonical types?");
2420
2421 // These types should never be variably-modified.
2422 case Type::Builtin:
2423 case Type::Complex:
2424 case Type::Vector:
2425 case Type::ExtVector:
2426 case Type::DependentSizedExtVector:
2427 case Type::ObjCObject:
2428 case Type::ObjCInterface:
2429 case Type::ObjCObjectPointer:
2430 case Type::Record:
2431 case Type::Enum:
2432 case Type::UnresolvedUsing:
2433 case Type::TypeOfExpr:
2434 case Type::TypeOf:
2435 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002436 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002437 case Type::DependentName:
2438 case Type::InjectedClassName:
2439 case Type::TemplateSpecialization:
2440 case Type::DependentTemplateSpecialization:
2441 case Type::TemplateTypeParm:
2442 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002443 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002444 case Type::PackExpansion:
2445 llvm_unreachable("type should never be variably-modified");
2446
2447 // These types can be variably-modified but should never need to
2448 // further decay.
2449 case Type::FunctionNoProto:
2450 case Type::FunctionProto:
2451 case Type::BlockPointer:
2452 case Type::MemberPointer:
2453 return type;
2454
2455 // These types can be variably-modified. All these modifications
2456 // preserve structure except as noted by comments.
2457 // TODO: if we ever care about optimizing VLAs, there are no-op
2458 // optimizations available here.
2459 case Type::Pointer:
2460 result = getPointerType(getVariableArrayDecayedType(
2461 cast<PointerType>(ty)->getPointeeType()));
2462 break;
2463
2464 case Type::LValueReference: {
2465 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2466 result = getLValueReferenceType(
2467 getVariableArrayDecayedType(lv->getPointeeType()),
2468 lv->isSpelledAsLValue());
2469 break;
2470 }
2471
2472 case Type::RValueReference: {
2473 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2474 result = getRValueReferenceType(
2475 getVariableArrayDecayedType(lv->getPointeeType()));
2476 break;
2477 }
2478
Eli Friedman0dfb8892011-10-06 23:00:33 +00002479 case Type::Atomic: {
2480 const AtomicType *at = cast<AtomicType>(ty);
2481 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2482 break;
2483 }
2484
John McCall06549462011-01-18 08:40:38 +00002485 case Type::ConstantArray: {
2486 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2487 result = getConstantArrayType(
2488 getVariableArrayDecayedType(cat->getElementType()),
2489 cat->getSize(),
2490 cat->getSizeModifier(),
2491 cat->getIndexTypeCVRQualifiers());
2492 break;
2493 }
2494
2495 case Type::DependentSizedArray: {
2496 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2497 result = getDependentSizedArrayType(
2498 getVariableArrayDecayedType(dat->getElementType()),
2499 dat->getSizeExpr(),
2500 dat->getSizeModifier(),
2501 dat->getIndexTypeCVRQualifiers(),
2502 dat->getBracketsRange());
2503 break;
2504 }
2505
2506 // Turn incomplete types into [*] types.
2507 case Type::IncompleteArray: {
2508 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2509 result = getVariableArrayType(
2510 getVariableArrayDecayedType(iat->getElementType()),
2511 /*size*/ 0,
2512 ArrayType::Normal,
2513 iat->getIndexTypeCVRQualifiers(),
2514 SourceRange());
2515 break;
2516 }
2517
2518 // Turn VLA types into [*] types.
2519 case Type::VariableArray: {
2520 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2521 result = getVariableArrayType(
2522 getVariableArrayDecayedType(vat->getElementType()),
2523 /*size*/ 0,
2524 ArrayType::Star,
2525 vat->getIndexTypeCVRQualifiers(),
2526 vat->getBracketsRange());
2527 break;
2528 }
2529 }
2530
2531 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002532 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002533}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002534
Steve Naroffcadebd02007-08-30 18:14:25 +00002535/// getVariableArrayType - Returns a non-unique reference to the type for a
2536/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002537QualType ASTContext::getVariableArrayType(QualType EltTy,
2538 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002539 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002540 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002541 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002542 // Since we don't unique expressions, it isn't possible to unique VLA's
2543 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002544 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002545
John McCall33ddac02011-01-19 10:06:00 +00002546 // Be sure to pull qualifiers off the element type.
2547 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2548 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002549 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002550 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002551 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002552 }
2553
John McCall90d1c2d2009-09-24 23:30:46 +00002554 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002555 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002556
2557 VariableArrayTypes.push_back(New);
2558 Types.push_back(New);
2559 return QualType(New, 0);
2560}
2561
Douglas Gregor4619e432008-12-05 23:32:09 +00002562/// getDependentSizedArrayType - Returns a non-unique reference to
2563/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002564/// type.
John McCall33ddac02011-01-19 10:06:00 +00002565QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2566 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002567 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002568 unsigned elementTypeQuals,
2569 SourceRange brackets) const {
2570 assert((!numElements || numElements->isTypeDependent() ||
2571 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002572 "Size must be type- or value-dependent!");
2573
John McCall33ddac02011-01-19 10:06:00 +00002574 // Dependently-sized array types that do not have a specified number
2575 // of elements will have their sizes deduced from a dependent
2576 // initializer. We do no canonicalization here at all, which is okay
2577 // because they can't be used in most locations.
2578 if (!numElements) {
2579 DependentSizedArrayType *newType
2580 = new (*this, TypeAlignment)
2581 DependentSizedArrayType(*this, elementType, QualType(),
2582 numElements, ASM, elementTypeQuals,
2583 brackets);
2584 Types.push_back(newType);
2585 return QualType(newType, 0);
2586 }
2587
2588 // Otherwise, we actually build a new type every time, but we
2589 // also build a canonical type.
2590
2591 SplitQualType canonElementType = getCanonicalType(elementType).split();
2592
2593 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002594 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002595 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002596 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002597 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002598
John McCall33ddac02011-01-19 10:06:00 +00002599 // Look for an existing type with these properties.
2600 DependentSizedArrayType *canonTy =
2601 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002602
John McCall33ddac02011-01-19 10:06:00 +00002603 // If we don't have one, build one.
2604 if (!canonTy) {
2605 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002606 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002607 QualType(), numElements, ASM, elementTypeQuals,
2608 brackets);
2609 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2610 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002611 }
2612
John McCall33ddac02011-01-19 10:06:00 +00002613 // Apply qualifiers from the element type to the array.
2614 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002615 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002616
John McCall33ddac02011-01-19 10:06:00 +00002617 // If we didn't need extra canonicalization for the element type,
2618 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002619 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002620 return canon;
2621
2622 // Otherwise, we need to build a type which follows the spelling
2623 // of the element type.
2624 DependentSizedArrayType *sugaredType
2625 = new (*this, TypeAlignment)
2626 DependentSizedArrayType(*this, elementType, canon, numElements,
2627 ASM, elementTypeQuals, brackets);
2628 Types.push_back(sugaredType);
2629 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002630}
2631
John McCall33ddac02011-01-19 10:06:00 +00002632QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002633 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002634 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002635 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002636 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002637
John McCall33ddac02011-01-19 10:06:00 +00002638 void *insertPos = 0;
2639 if (IncompleteArrayType *iat =
2640 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2641 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002642
2643 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002644 // either, so fill in the canonical type field. We also have to pull
2645 // qualifiers off the element type.
2646 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002647
John McCall33ddac02011-01-19 10:06:00 +00002648 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2649 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002650 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002651 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002652 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002653
2654 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002655 IncompleteArrayType *existing =
2656 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2657 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002658 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002659
John McCall33ddac02011-01-19 10:06:00 +00002660 IncompleteArrayType *newType = new (*this, TypeAlignment)
2661 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002662
John McCall33ddac02011-01-19 10:06:00 +00002663 IncompleteArrayTypes.InsertNode(newType, insertPos);
2664 Types.push_back(newType);
2665 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002666}
2667
Steve Naroff91fcddb2007-07-18 18:00:27 +00002668/// getVectorType - Return the unique reference to a vector type of
2669/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002670QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002671 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002672 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002673
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002674 // Check if we've already instantiated a vector of this type.
2675 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002676 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002677
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002678 void *InsertPos = 0;
2679 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2680 return QualType(VTP, 0);
2681
2682 // If the element type isn't canonical, this won't be a canonical type either,
2683 // so fill in the canonical type field.
2684 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002685 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002686 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002687
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002688 // Get the new insert position for the node we care about.
2689 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002690 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002691 }
John McCall90d1c2d2009-09-24 23:30:46 +00002692 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002693 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002694 VectorTypes.InsertNode(New, InsertPos);
2695 Types.push_back(New);
2696 return QualType(New, 0);
2697}
2698
Nate Begemance4d7fc2008-04-18 23:10:10 +00002699/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002700/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002701QualType
2702ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002703 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002704
Steve Naroff91fcddb2007-07-18 18:00:27 +00002705 // Check if we've already instantiated a vector of this type.
2706 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002707 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002708 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002709 void *InsertPos = 0;
2710 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2711 return QualType(VTP, 0);
2712
2713 // If the element type isn't canonical, this won't be a canonical type either,
2714 // so fill in the canonical type field.
2715 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002716 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002717 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002718
Steve Naroff91fcddb2007-07-18 18:00:27 +00002719 // Get the new insert position for the node we care about.
2720 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002721 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002722 }
John McCall90d1c2d2009-09-24 23:30:46 +00002723 ExtVectorType *New = new (*this, TypeAlignment)
2724 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002725 VectorTypes.InsertNode(New, InsertPos);
2726 Types.push_back(New);
2727 return QualType(New, 0);
2728}
2729
Jay Foad39c79802011-01-12 09:06:06 +00002730QualType
2731ASTContext::getDependentSizedExtVectorType(QualType vecType,
2732 Expr *SizeExpr,
2733 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002734 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002735 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002736 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002737
Douglas Gregor352169a2009-07-31 03:54:25 +00002738 void *InsertPos = 0;
2739 DependentSizedExtVectorType *Canon
2740 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2741 DependentSizedExtVectorType *New;
2742 if (Canon) {
2743 // We already have a canonical version of this array type; use it as
2744 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002745 New = new (*this, TypeAlignment)
2746 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2747 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002748 } else {
2749 QualType CanonVecTy = getCanonicalType(vecType);
2750 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002751 New = new (*this, TypeAlignment)
2752 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2753 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002754
2755 DependentSizedExtVectorType *CanonCheck
2756 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2757 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2758 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002759 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2760 } else {
2761 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2762 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002763 New = new (*this, TypeAlignment)
2764 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002765 }
2766 }
Mike Stump11289f42009-09-09 15:08:12 +00002767
Douglas Gregor758a8692009-06-17 21:51:59 +00002768 Types.push_back(New);
2769 return QualType(New, 0);
2770}
2771
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002772/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002773///
Jay Foad39c79802011-01-12 09:06:06 +00002774QualType
2775ASTContext::getFunctionNoProtoType(QualType ResultTy,
2776 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002777 const CallingConv CallConv = Info.getCC();
2778
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002779 // Unique functions, to guarantee there is only one function of a particular
2780 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002781 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002782 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002783
Chris Lattner47955de2007-01-27 08:37:20 +00002784 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002785 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002786 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002787 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002788
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002789 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002790 if (!ResultTy.isCanonical()) {
2791 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002792
Chris Lattner47955de2007-01-27 08:37:20 +00002793 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002794 FunctionNoProtoType *NewIP =
2795 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002796 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002797 }
Mike Stump11289f42009-09-09 15:08:12 +00002798
Roman Divacky65b88cd2011-03-01 17:40:53 +00002799 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002800 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002801 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002802 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002803 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002804 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002805}
2806
Douglas Gregorcd780372013-01-17 23:36:45 +00002807/// \brief Determine whether \p T is canonical as the result type of a function.
2808static bool isCanonicalResultType(QualType T) {
2809 return T.isCanonical() &&
2810 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2811 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2812}
2813
Jay Foad39c79802011-01-12 09:06:06 +00002814QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002815ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002816 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002817 size_t NumArgs = ArgArray.size();
2818
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002819 // Unique functions, to guarantee there is only one function of a particular
2820 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002821 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002822 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2823 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002824
2825 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002826 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002827 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002828 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002829
2830 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002831 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002832 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002833 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002834 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002835 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002836 isCanonical = false;
2837
2838 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002839 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002840 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002841 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002842 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002843 CanonicalArgs.reserve(NumArgs);
2844 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002845 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002846
John McCalldb40c7f2010-12-14 08:05:40 +00002847 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002848 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002849 CanonicalEPI.ExceptionSpecType = EST_None;
2850 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002851
Douglas Gregorcd780372013-01-17 23:36:45 +00002852 // Result types do not have ARC lifetime qualifiers.
2853 QualType CanResultTy = getCanonicalType(ResultTy);
2854 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2855 Qualifiers Qs = CanResultTy.getQualifiers();
2856 Qs.removeObjCLifetime();
2857 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2858 }
2859
Jordan Rose5c382722013-03-08 21:51:21 +00002860 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002861
Chris Lattnerfd4de792007-01-27 01:15:32 +00002862 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002863 FunctionProtoType *NewIP =
2864 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002865 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002866 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002867
John McCall31168b02011-06-15 23:02:42 +00002868 // FunctionProtoType objects are allocated with extra bytes after
2869 // them for three variable size arrays at the end:
2870 // - parameter types
2871 // - exception types
2872 // - consumed-arguments flags
2873 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002874 // expression, or information used to resolve the exception
2875 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002876 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002877 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002878 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002879 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002880 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002881 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002882 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002883 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002884 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2885 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002886 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002887 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002888 Size += NumArgs * sizeof(bool);
2889
John McCalldb40c7f2010-12-14 08:05:40 +00002890 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002891 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002892 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002893 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002894 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002895 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002896}
Chris Lattneref51c202006-11-10 07:17:23 +00002897
John McCalle78aac42010-03-10 03:28:59 +00002898#ifndef NDEBUG
2899static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2900 if (!isa<CXXRecordDecl>(D)) return false;
2901 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2902 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2903 return true;
2904 if (RD->getDescribedClassTemplate() &&
2905 !isa<ClassTemplateSpecializationDecl>(RD))
2906 return true;
2907 return false;
2908}
2909#endif
2910
2911/// getInjectedClassNameType - Return the unique reference to the
2912/// injected class name type for the specified templated declaration.
2913QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002914 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002915 assert(NeedsInjectedClassNameType(Decl));
2916 if (Decl->TypeForDecl) {
2917 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002918 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002919 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2920 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2921 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2922 } else {
John McCall424cec92011-01-19 06:33:43 +00002923 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002924 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002925 Decl->TypeForDecl = newType;
2926 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002927 }
2928 return QualType(Decl->TypeForDecl, 0);
2929}
2930
Douglas Gregor83a586e2008-04-13 21:07:44 +00002931/// getTypeDeclType - Return the unique reference to the type for the
2932/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002933QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002934 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002935 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002936
Richard Smithdda56e42011-04-15 14:24:37 +00002937 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002938 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002939
John McCall96f0b5f2010-03-10 06:48:02 +00002940 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2941 "Template type parameter types are always available.");
2942
John McCall81e38502010-02-16 03:57:14 +00002943 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002944 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002945 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002946 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002947 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002948 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002949 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002950 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002951 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002952 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2953 Decl->TypeForDecl = newType;
2954 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002955 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002956 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002957
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002958 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002959}
2960
Chris Lattner32d920b2007-01-26 02:01:53 +00002961/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002962/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002963QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002964ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2965 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002966 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002967
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002968 if (Canonical.isNull())
2969 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002970 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002971 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002972 Decl->TypeForDecl = newType;
2973 Types.push_back(newType);
2974 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002975}
2976
Jay Foad39c79802011-01-12 09:06:06 +00002977QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002978 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2979
Douglas Gregorec9fd132012-01-14 16:38:05 +00002980 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002981 if (PrevDecl->TypeForDecl)
2982 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2983
John McCall424cec92011-01-19 06:33:43 +00002984 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2985 Decl->TypeForDecl = newType;
2986 Types.push_back(newType);
2987 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002988}
2989
Jay Foad39c79802011-01-12 09:06:06 +00002990QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002991 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2992
Douglas Gregorec9fd132012-01-14 16:38:05 +00002993 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002994 if (PrevDecl->TypeForDecl)
2995 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2996
John McCall424cec92011-01-19 06:33:43 +00002997 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2998 Decl->TypeForDecl = newType;
2999 Types.push_back(newType);
3000 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003001}
3002
John McCall81904512011-01-06 01:58:22 +00003003QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3004 QualType modifiedType,
3005 QualType equivalentType) {
3006 llvm::FoldingSetNodeID id;
3007 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3008
3009 void *insertPos = 0;
3010 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3011 if (type) return QualType(type, 0);
3012
3013 QualType canon = getCanonicalType(equivalentType);
3014 type = new (*this, TypeAlignment)
3015 AttributedType(canon, attrKind, modifiedType, equivalentType);
3016
3017 Types.push_back(type);
3018 AttributedTypes.InsertNode(type, insertPos);
3019
3020 return QualType(type, 0);
3021}
3022
3023
John McCallcebee162009-10-18 09:09:24 +00003024/// \brief Retrieve a substitution-result type.
3025QualType
3026ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003027 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003028 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003029 && "replacement types must always be canonical");
3030
3031 llvm::FoldingSetNodeID ID;
3032 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3033 void *InsertPos = 0;
3034 SubstTemplateTypeParmType *SubstParm
3035 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3036
3037 if (!SubstParm) {
3038 SubstParm = new (*this, TypeAlignment)
3039 SubstTemplateTypeParmType(Parm, Replacement);
3040 Types.push_back(SubstParm);
3041 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3042 }
3043
3044 return QualType(SubstParm, 0);
3045}
3046
Douglas Gregorada4b792011-01-14 02:55:32 +00003047/// \brief Retrieve a
3048QualType ASTContext::getSubstTemplateTypeParmPackType(
3049 const TemplateTypeParmType *Parm,
3050 const TemplateArgument &ArgPack) {
3051#ifndef NDEBUG
3052 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3053 PEnd = ArgPack.pack_end();
3054 P != PEnd; ++P) {
3055 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3056 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3057 }
3058#endif
3059
3060 llvm::FoldingSetNodeID ID;
3061 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3062 void *InsertPos = 0;
3063 if (SubstTemplateTypeParmPackType *SubstParm
3064 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3065 return QualType(SubstParm, 0);
3066
3067 QualType Canon;
3068 if (!Parm->isCanonicalUnqualified()) {
3069 Canon = getCanonicalType(QualType(Parm, 0));
3070 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3071 ArgPack);
3072 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3073 }
3074
3075 SubstTemplateTypeParmPackType *SubstParm
3076 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3077 ArgPack);
3078 Types.push_back(SubstParm);
3079 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3080 return QualType(SubstParm, 0);
3081}
3082
Douglas Gregoreff93e02009-02-05 23:33:38 +00003083/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003084/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003085/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003086QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003087 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003088 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003089 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003090 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003091 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003092 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003093 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3094
3095 if (TypeParm)
3096 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003097
Chandler Carruth08836322011-05-01 00:51:33 +00003098 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003099 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003100 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003101
3102 TemplateTypeParmType *TypeCheck
3103 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3104 assert(!TypeCheck && "Template type parameter canonical type broken");
3105 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003106 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003107 TypeParm = new (*this, TypeAlignment)
3108 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003109
3110 Types.push_back(TypeParm);
3111 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3112
3113 return QualType(TypeParm, 0);
3114}
3115
John McCalle78aac42010-03-10 03:28:59 +00003116TypeSourceInfo *
3117ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3118 SourceLocation NameLoc,
3119 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003120 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003121 assert(!Name.getAsDependentTemplateName() &&
3122 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003123 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003124
3125 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003126 TemplateSpecializationTypeLoc TL =
3127 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003128 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003129 TL.setTemplateNameLoc(NameLoc);
3130 TL.setLAngleLoc(Args.getLAngleLoc());
3131 TL.setRAngleLoc(Args.getRAngleLoc());
3132 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3133 TL.setArgLocInfo(i, Args[i].getLocInfo());
3134 return DI;
3135}
3136
Mike Stump11289f42009-09-09 15:08:12 +00003137QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003138ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003139 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003140 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003141 assert(!Template.getAsDependentTemplateName() &&
3142 "No dependent template names here!");
3143
John McCall6b51f282009-11-23 01:53:49 +00003144 unsigned NumArgs = Args.size();
3145
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003146 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003147 ArgVec.reserve(NumArgs);
3148 for (unsigned i = 0; i != NumArgs; ++i)
3149 ArgVec.push_back(Args[i].getArgument());
3150
John McCall2408e322010-04-27 00:57:59 +00003151 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003152 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003153}
3154
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003155#ifndef NDEBUG
3156static bool hasAnyPackExpansions(const TemplateArgument *Args,
3157 unsigned NumArgs) {
3158 for (unsigned I = 0; I != NumArgs; ++I)
3159 if (Args[I].isPackExpansion())
3160 return true;
3161
3162 return true;
3163}
3164#endif
3165
John McCall0ad16662009-10-29 08:12:44 +00003166QualType
3167ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003168 const TemplateArgument *Args,
3169 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003170 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003171 assert(!Template.getAsDependentTemplateName() &&
3172 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003173 // Look through qualified template names.
3174 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3175 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003176
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003177 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003178 Template.getAsTemplateDecl() &&
3179 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003180 QualType CanonType;
3181 if (!Underlying.isNull())
3182 CanonType = getCanonicalType(Underlying);
3183 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003184 // We can get here with an alias template when the specialization contains
3185 // a pack expansion that does not match up with a parameter pack.
3186 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3187 "Caller must compute aliased type");
3188 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003189 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3190 NumArgs);
3191 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003192
Douglas Gregora8e02e72009-07-28 23:00:59 +00003193 // Allocate the (non-canonical) template specialization type, but don't
3194 // try to unique it: these types typically have location information that
3195 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003196 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3197 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003198 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003199 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003200 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003201 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3202 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003203
Douglas Gregor8bf42052009-02-09 18:46:07 +00003204 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003205 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003206}
3207
Mike Stump11289f42009-09-09 15:08:12 +00003208QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003209ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3210 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003211 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003212 assert(!Template.getAsDependentTemplateName() &&
3213 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003214
Douglas Gregore29139c2011-03-03 17:04:51 +00003215 // Look through qualified template names.
3216 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3217 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003218
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003219 // Build the canonical template specialization type.
3220 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003221 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003222 CanonArgs.reserve(NumArgs);
3223 for (unsigned I = 0; I != NumArgs; ++I)
3224 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3225
3226 // Determine whether this canonical template specialization type already
3227 // exists.
3228 llvm::FoldingSetNodeID ID;
3229 TemplateSpecializationType::Profile(ID, CanonTemplate,
3230 CanonArgs.data(), NumArgs, *this);
3231
3232 void *InsertPos = 0;
3233 TemplateSpecializationType *Spec
3234 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3235
3236 if (!Spec) {
3237 // Allocate a new canonical template specialization type.
3238 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3239 sizeof(TemplateArgument) * NumArgs),
3240 TypeAlignment);
3241 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3242 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003243 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003244 Types.push_back(Spec);
3245 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3246 }
3247
3248 assert(Spec->isDependentType() &&
3249 "Non-dependent template-id type must have a canonical type");
3250 return QualType(Spec, 0);
3251}
3252
3253QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003254ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3255 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003256 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003257 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003258 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003259
3260 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003261 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003262 if (T)
3263 return QualType(T, 0);
3264
Douglas Gregorc42075a2010-02-04 18:10:26 +00003265 QualType Canon = NamedType;
3266 if (!Canon.isCanonical()) {
3267 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003268 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3269 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003270 (void)CheckT;
3271 }
3272
Abramo Bagnara6150c882010-05-11 21:36:43 +00003273 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003274 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003275 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003276 return QualType(T, 0);
3277}
3278
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003279QualType
Jay Foad39c79802011-01-12 09:06:06 +00003280ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003281 llvm::FoldingSetNodeID ID;
3282 ParenType::Profile(ID, InnerType);
3283
3284 void *InsertPos = 0;
3285 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3286 if (T)
3287 return QualType(T, 0);
3288
3289 QualType Canon = InnerType;
3290 if (!Canon.isCanonical()) {
3291 Canon = getCanonicalType(InnerType);
3292 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3293 assert(!CheckT && "Paren canonical type broken");
3294 (void)CheckT;
3295 }
3296
3297 T = new (*this) ParenType(InnerType, Canon);
3298 Types.push_back(T);
3299 ParenTypes.InsertNode(T, InsertPos);
3300 return QualType(T, 0);
3301}
3302
Douglas Gregor02085352010-03-31 20:19:30 +00003303QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3304 NestedNameSpecifier *NNS,
3305 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003306 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003307 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3308
3309 if (Canon.isNull()) {
3310 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003311 ElaboratedTypeKeyword CanonKeyword = Keyword;
3312 if (Keyword == ETK_None)
3313 CanonKeyword = ETK_Typename;
3314
3315 if (CanonNNS != NNS || CanonKeyword != Keyword)
3316 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003317 }
3318
3319 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003320 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003321
3322 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003323 DependentNameType *T
3324 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003325 if (T)
3326 return QualType(T, 0);
3327
Douglas Gregor02085352010-03-31 20:19:30 +00003328 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003329 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003330 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003331 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003332}
3333
Mike Stump11289f42009-09-09 15:08:12 +00003334QualType
John McCallc392f372010-06-11 00:33:02 +00003335ASTContext::getDependentTemplateSpecializationType(
3336 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003337 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003338 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003339 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003340 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003341 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003342 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3343 ArgCopy.push_back(Args[I].getArgument());
3344 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3345 ArgCopy.size(),
3346 ArgCopy.data());
3347}
3348
3349QualType
3350ASTContext::getDependentTemplateSpecializationType(
3351 ElaboratedTypeKeyword Keyword,
3352 NestedNameSpecifier *NNS,
3353 const IdentifierInfo *Name,
3354 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003355 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003356 assert((!NNS || NNS->isDependent()) &&
3357 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003358
Douglas Gregorc42075a2010-02-04 18:10:26 +00003359 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003360 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3361 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003362
3363 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003364 DependentTemplateSpecializationType *T
3365 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003366 if (T)
3367 return QualType(T, 0);
3368
John McCallc392f372010-06-11 00:33:02 +00003369 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003370
John McCallc392f372010-06-11 00:33:02 +00003371 ElaboratedTypeKeyword CanonKeyword = Keyword;
3372 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3373
3374 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003375 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003376 for (unsigned I = 0; I != NumArgs; ++I) {
3377 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3378 if (!CanonArgs[I].structurallyEquals(Args[I]))
3379 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003380 }
3381
John McCallc392f372010-06-11 00:33:02 +00003382 QualType Canon;
3383 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3384 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3385 Name, NumArgs,
3386 CanonArgs.data());
3387
3388 // Find the insert position again.
3389 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3390 }
3391
3392 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3393 sizeof(TemplateArgument) * NumArgs),
3394 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003395 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003396 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003397 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003398 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003399 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003400}
3401
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003402QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003403 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003404 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003405 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003406
3407 assert(Pattern->containsUnexpandedParameterPack() &&
3408 "Pack expansions must expand one or more parameter packs");
3409 void *InsertPos = 0;
3410 PackExpansionType *T
3411 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3412 if (T)
3413 return QualType(T, 0);
3414
3415 QualType Canon;
3416 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003417 Canon = getCanonicalType(Pattern);
3418 // The canonical type might not contain an unexpanded parameter pack, if it
3419 // contains an alias template specialization which ignores one of its
3420 // parameters.
3421 if (Canon->containsUnexpandedParameterPack()) {
3422 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003423
Richard Smith68eea502012-07-16 00:20:35 +00003424 // Find the insert position again, in case we inserted an element into
3425 // PackExpansionTypes and invalidated our insert position.
3426 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3427 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003428 }
3429
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003430 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003431 Types.push_back(T);
3432 PackExpansionTypes.InsertNode(T, InsertPos);
3433 return QualType(T, 0);
3434}
3435
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003436/// CmpProtocolNames - Comparison predicate for sorting protocols
3437/// alphabetically.
3438static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3439 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003440 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003441}
3442
John McCall8b07ec22010-05-15 11:32:37 +00003443static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003444 unsigned NumProtocols) {
3445 if (NumProtocols == 0) return true;
3446
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003447 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3448 return false;
3449
John McCallfc93cf92009-10-22 22:37:11 +00003450 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003451 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3452 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003453 return false;
3454 return true;
3455}
3456
3457static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003458 unsigned &NumProtocols) {
3459 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003460
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003461 // Sort protocols, keyed by name.
3462 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3463
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003464 // Canonicalize.
3465 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3466 Protocols[I] = Protocols[I]->getCanonicalDecl();
3467
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003468 // Remove duplicates.
3469 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3470 NumProtocols = ProtocolsEnd-Protocols;
3471}
3472
John McCall8b07ec22010-05-15 11:32:37 +00003473QualType ASTContext::getObjCObjectType(QualType BaseType,
3474 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003475 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003476 // If the base type is an interface and there aren't any protocols
3477 // to add, then the interface type will do just fine.
3478 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3479 return BaseType;
3480
3481 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003482 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003483 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003484 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003485 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3486 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003487
John McCall8b07ec22010-05-15 11:32:37 +00003488 // Build the canonical type, which has the canonical base type and
3489 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003490 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003491 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3492 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3493 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003494 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003495 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003496 unsigned UniqueCount = NumProtocols;
3497
John McCallfc93cf92009-10-22 22:37:11 +00003498 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003499 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3500 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003501 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003502 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3503 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003504 }
3505
3506 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003507 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3508 }
3509
3510 unsigned Size = sizeof(ObjCObjectTypeImpl);
3511 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3512 void *Mem = Allocate(Size, TypeAlignment);
3513 ObjCObjectTypeImpl *T =
3514 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3515
3516 Types.push_back(T);
3517 ObjCObjectTypes.InsertNode(T, InsertPos);
3518 return QualType(T, 0);
3519}
3520
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003521/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3522/// protocol list adopt all protocols in QT's qualified-id protocol
3523/// list.
3524bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3525 ObjCInterfaceDecl *IC) {
3526 if (!QT->isObjCQualifiedIdType())
3527 return false;
3528
3529 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3530 // If both the right and left sides have qualifiers.
3531 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3532 E = OPT->qual_end(); I != E; ++I) {
3533 ObjCProtocolDecl *Proto = *I;
3534 if (!IC->ClassImplementsProtocol(Proto, false))
3535 return false;
3536 }
3537 return true;
3538 }
3539 return false;
3540}
3541
3542/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3543/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3544/// of protocols.
3545bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3546 ObjCInterfaceDecl *IDecl) {
3547 if (!QT->isObjCQualifiedIdType())
3548 return false;
3549 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3550 if (!OPT)
3551 return false;
3552 if (!IDecl->hasDefinition())
3553 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003554 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3555 CollectInheritedProtocols(IDecl, InheritedProtocols);
3556 if (InheritedProtocols.empty())
3557 return false;
3558
3559 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3560 InheritedProtocols.begin(),
3561 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003562 // If both the right and left sides have qualifiers.
3563 bool Adopts = false;
3564 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3565 E = OPT->qual_end(); I != E; ++I) {
3566 ObjCProtocolDecl *Proto = *I;
3567 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3568 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3569 break;
3570 }
3571 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003572 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003573 }
3574 return true;
3575}
3576
John McCall8b07ec22010-05-15 11:32:37 +00003577/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3578/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003579QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003580 llvm::FoldingSetNodeID ID;
3581 ObjCObjectPointerType::Profile(ID, ObjectT);
3582
3583 void *InsertPos = 0;
3584 if (ObjCObjectPointerType *QT =
3585 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3586 return QualType(QT, 0);
3587
3588 // Find the canonical object type.
3589 QualType Canonical;
3590 if (!ObjectT.isCanonical()) {
3591 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3592
3593 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003594 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3595 }
3596
Douglas Gregorf85bee62010-02-08 22:59:26 +00003597 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003598 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3599 ObjCObjectPointerType *QType =
3600 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003601
Steve Narofffb4330f2009-06-17 22:40:22 +00003602 Types.push_back(QType);
3603 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003604 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003605}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003606
Douglas Gregor1c283312010-08-11 12:19:30 +00003607/// getObjCInterfaceType - Return the unique reference to the type for the
3608/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003609QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3610 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003611 if (Decl->TypeForDecl)
3612 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003613
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003614 if (PrevDecl) {
3615 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3616 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3617 return QualType(PrevDecl->TypeForDecl, 0);
3618 }
3619
Douglas Gregor7671e532011-12-16 16:34:57 +00003620 // Prefer the definition, if there is one.
3621 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3622 Decl = Def;
3623
Douglas Gregor1c283312010-08-11 12:19:30 +00003624 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3625 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3626 Decl->TypeForDecl = T;
3627 Types.push_back(T);
3628 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003629}
3630
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003631/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3632/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003633/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003634/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003635/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003636QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003637 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003638 if (tofExpr->isTypeDependent()) {
3639 llvm::FoldingSetNodeID ID;
3640 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003641
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003642 void *InsertPos = 0;
3643 DependentTypeOfExprType *Canon
3644 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3645 if (Canon) {
3646 // We already have a "canonical" version of an identical, dependent
3647 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003648 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003649 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003650 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003651 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003652 Canon
3653 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003654 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3655 toe = Canon;
3656 }
3657 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003658 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003659 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003660 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003661 Types.push_back(toe);
3662 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003663}
3664
Steve Naroffa773cd52007-08-01 18:02:17 +00003665/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3666/// TypeOfType AST's. The only motivation to unique these nodes would be
3667/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003668/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003669/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003670QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003671 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003672 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003673 Types.push_back(tot);
3674 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003675}
3676
Anders Carlssonad6bd352009-06-24 21:24:56 +00003677
Anders Carlsson81df7b82009-06-24 19:06:50 +00003678/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3679/// DecltypeType AST's. The only motivation to unique these nodes would be
3680/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003681/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003682/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003683QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003684 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003685
3686 // C++0x [temp.type]p2:
3687 // If an expression e involves a template parameter, decltype(e) denotes a
3688 // unique dependent type. Two such decltype-specifiers refer to the same
3689 // type only if their expressions are equivalent (14.5.6.1).
3690 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003691 llvm::FoldingSetNodeID ID;
3692 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003693
Douglas Gregora21f6c32009-07-30 23:36:40 +00003694 void *InsertPos = 0;
3695 DependentDecltypeType *Canon
3696 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3697 if (Canon) {
3698 // We already have a "canonical" version of an equivalent, dependent
3699 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003700 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003701 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003702 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003703 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003704 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003705 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3706 dt = Canon;
3707 }
3708 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003709 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3710 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003711 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003712 Types.push_back(dt);
3713 return QualType(dt, 0);
3714}
3715
Alexis Hunte852b102011-05-24 22:41:36 +00003716/// getUnaryTransformationType - We don't unique these, since the memory
3717/// savings are minimal and these are rare.
3718QualType ASTContext::getUnaryTransformType(QualType BaseType,
3719 QualType UnderlyingType,
3720 UnaryTransformType::UTTKind Kind)
3721 const {
3722 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003723 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3724 Kind,
3725 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003726 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003727 Types.push_back(Ty);
3728 return QualType(Ty, 0);
3729}
3730
Richard Smith2a7d4812013-05-04 07:00:32 +00003731/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3732/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3733/// canonical deduced-but-dependent 'auto' type.
3734QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003735 bool IsDependent) const {
3736 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003737 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003738
Richard Smith2a7d4812013-05-04 07:00:32 +00003739 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003740 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003741 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003742 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003743 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3744 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003745
Richard Smith74aeef52013-04-26 16:15:35 +00003746 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003747 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003748 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003749 Types.push_back(AT);
3750 if (InsertPos)
3751 AutoTypes.InsertNode(AT, InsertPos);
3752 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003753}
3754
Eli Friedman0dfb8892011-10-06 23:00:33 +00003755/// getAtomicType - Return the uniqued reference to the atomic type for
3756/// the given value type.
3757QualType ASTContext::getAtomicType(QualType T) const {
3758 // Unique pointers, to guarantee there is only one pointer of a particular
3759 // structure.
3760 llvm::FoldingSetNodeID ID;
3761 AtomicType::Profile(ID, T);
3762
3763 void *InsertPos = 0;
3764 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3765 return QualType(AT, 0);
3766
3767 // If the atomic value type isn't canonical, this won't be a canonical type
3768 // either, so fill in the canonical type field.
3769 QualType Canonical;
3770 if (!T.isCanonical()) {
3771 Canonical = getAtomicType(getCanonicalType(T));
3772
3773 // Get the new insert position for the node we care about.
3774 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3775 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3776 }
3777 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3778 Types.push_back(New);
3779 AtomicTypes.InsertNode(New, InsertPos);
3780 return QualType(New, 0);
3781}
3782
Richard Smith02e85f32011-04-14 22:09:26 +00003783/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3784QualType ASTContext::getAutoDeductType() const {
3785 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003786 AutoDeductTy = QualType(
3787 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003788 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003789 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003790 return AutoDeductTy;
3791}
3792
3793/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3794QualType ASTContext::getAutoRRefDeductType() const {
3795 if (AutoRRefDeductTy.isNull())
3796 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3797 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3798 return AutoRRefDeductTy;
3799}
3800
Chris Lattnerfb072462007-01-23 05:45:31 +00003801/// getTagDeclType - Return the unique reference to the type for the
3802/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003803QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003804 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003805 // FIXME: What is the design on getTagDeclType when it requires casting
3806 // away const? mutable?
3807 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003808}
3809
Mike Stump11289f42009-09-09 15:08:12 +00003810/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3811/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3812/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003813CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003814 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003815}
Chris Lattnerfb072462007-01-23 05:45:31 +00003816
Hans Wennborg27541db2011-10-27 08:29:09 +00003817/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3818CanQualType ASTContext::getIntMaxType() const {
3819 return getFromTargetType(Target->getIntMaxType());
3820}
3821
3822/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3823CanQualType ASTContext::getUIntMaxType() const {
3824 return getFromTargetType(Target->getUIntMaxType());
3825}
3826
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003827/// getSignedWCharType - Return the type of "signed wchar_t".
3828/// Used when in C++, as a GCC extension.
3829QualType ASTContext::getSignedWCharType() const {
3830 // FIXME: derive from "Target" ?
3831 return WCharTy;
3832}
3833
3834/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3835/// Used when in C++, as a GCC extension.
3836QualType ASTContext::getUnsignedWCharType() const {
3837 // FIXME: derive from "Target" ?
3838 return UnsignedIntTy;
3839}
3840
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003841QualType ASTContext::getIntPtrType() const {
3842 return getFromTargetType(Target->getIntPtrType());
3843}
3844
3845QualType ASTContext::getUIntPtrType() const {
3846 return getCorrespondingUnsignedType(getIntPtrType());
3847}
3848
Hans Wennborg27541db2011-10-27 08:29:09 +00003849/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003850/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3851QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003852 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003853}
3854
Eli Friedman4e91899e2012-11-27 02:58:24 +00003855/// \brief Return the unique type for "pid_t" defined in
3856/// <sys/types.h>. We need this to compute the correct type for vfork().
3857QualType ASTContext::getProcessIDType() const {
3858 return getFromTargetType(Target->getProcessIDType());
3859}
3860
Chris Lattnera21ad802008-04-02 05:18:44 +00003861//===----------------------------------------------------------------------===//
3862// Type Operators
3863//===----------------------------------------------------------------------===//
3864
Jay Foad39c79802011-01-12 09:06:06 +00003865CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003866 // Push qualifiers into arrays, and then discard any remaining
3867 // qualifiers.
3868 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003869 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003870 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003871 QualType Result;
3872 if (isa<ArrayType>(Ty)) {
3873 Result = getArrayDecayedType(QualType(Ty,0));
3874 } else if (isa<FunctionType>(Ty)) {
3875 Result = getPointerType(QualType(Ty, 0));
3876 } else {
3877 Result = QualType(Ty, 0);
3878 }
3879
3880 return CanQualType::CreateUnsafe(Result);
3881}
3882
John McCall6c9dd522011-01-18 07:41:22 +00003883QualType ASTContext::getUnqualifiedArrayType(QualType type,
3884 Qualifiers &quals) {
3885 SplitQualType splitType = type.getSplitUnqualifiedType();
3886
3887 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3888 // the unqualified desugared type and then drops it on the floor.
3889 // We then have to strip that sugar back off with
3890 // getUnqualifiedDesugaredType(), which is silly.
3891 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003892 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003893
3894 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003895 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003896 quals = splitType.Quals;
3897 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003898 }
3899
John McCall6c9dd522011-01-18 07:41:22 +00003900 // Otherwise, recurse on the array's element type.
3901 QualType elementType = AT->getElementType();
3902 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3903
3904 // If that didn't change the element type, AT has no qualifiers, so we
3905 // can just use the results in splitType.
3906 if (elementType == unqualElementType) {
3907 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003908 quals = splitType.Quals;
3909 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003910 }
3911
3912 // Otherwise, add in the qualifiers from the outermost type, then
3913 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003914 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003915
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003916 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003917 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003918 CAT->getSizeModifier(), 0);
3919 }
3920
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003921 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003922 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003923 }
3924
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003925 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003926 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003927 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003928 VAT->getSizeModifier(),
3929 VAT->getIndexTypeCVRQualifiers(),
3930 VAT->getBracketsRange());
3931 }
3932
3933 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003934 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003935 DSAT->getSizeModifier(), 0,
3936 SourceRange());
3937}
3938
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003939/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3940/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3941/// they point to and return true. If T1 and T2 aren't pointer types
3942/// or pointer-to-member types, or if they are not similar at this
3943/// level, returns false and leaves T1 and T2 unchanged. Top-level
3944/// qualifiers on T1 and T2 are ignored. This function will typically
3945/// be called in a loop that successively "unwraps" pointer and
3946/// pointer-to-member types to compare them at each level.
3947bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3948 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3949 *T2PtrType = T2->getAs<PointerType>();
3950 if (T1PtrType && T2PtrType) {
3951 T1 = T1PtrType->getPointeeType();
3952 T2 = T2PtrType->getPointeeType();
3953 return true;
3954 }
3955
3956 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3957 *T2MPType = T2->getAs<MemberPointerType>();
3958 if (T1MPType && T2MPType &&
3959 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3960 QualType(T2MPType->getClass(), 0))) {
3961 T1 = T1MPType->getPointeeType();
3962 T2 = T2MPType->getPointeeType();
3963 return true;
3964 }
3965
David Blaikiebbafb8a2012-03-11 07:00:24 +00003966 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003967 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3968 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3969 if (T1OPType && T2OPType) {
3970 T1 = T1OPType->getPointeeType();
3971 T2 = T2OPType->getPointeeType();
3972 return true;
3973 }
3974 }
3975
3976 // FIXME: Block pointers, too?
3977
3978 return false;
3979}
3980
Jay Foad39c79802011-01-12 09:06:06 +00003981DeclarationNameInfo
3982ASTContext::getNameForTemplate(TemplateName Name,
3983 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003984 switch (Name.getKind()) {
3985 case TemplateName::QualifiedTemplate:
3986 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003987 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003988 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3989 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003990
John McCalld9dfe3a2011-06-30 08:33:18 +00003991 case TemplateName::OverloadedTemplate: {
3992 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3993 // DNInfo work in progress: CHECKME: what about DNLoc?
3994 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3995 }
3996
3997 case TemplateName::DependentTemplate: {
3998 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003999 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004000 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004001 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4002 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004003 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004004 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4005 // DNInfo work in progress: FIXME: source locations?
4006 DeclarationNameLoc DNLoc;
4007 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4008 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4009 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004010 }
4011 }
4012
John McCalld9dfe3a2011-06-30 08:33:18 +00004013 case TemplateName::SubstTemplateTemplateParm: {
4014 SubstTemplateTemplateParmStorage *subst
4015 = Name.getAsSubstTemplateTemplateParm();
4016 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4017 NameLoc);
4018 }
4019
4020 case TemplateName::SubstTemplateTemplateParmPack: {
4021 SubstTemplateTemplateParmPackStorage *subst
4022 = Name.getAsSubstTemplateTemplateParmPack();
4023 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4024 NameLoc);
4025 }
4026 }
4027
4028 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004029}
4030
Jay Foad39c79802011-01-12 09:06:06 +00004031TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004032 switch (Name.getKind()) {
4033 case TemplateName::QualifiedTemplate:
4034 case TemplateName::Template: {
4035 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004036 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004037 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004038 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4039
4040 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004041 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004042 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004043
John McCalld9dfe3a2011-06-30 08:33:18 +00004044 case TemplateName::OverloadedTemplate:
4045 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004046
John McCalld9dfe3a2011-06-30 08:33:18 +00004047 case TemplateName::DependentTemplate: {
4048 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4049 assert(DTN && "Non-dependent template names must refer to template decls.");
4050 return DTN->CanonicalTemplateName;
4051 }
4052
4053 case TemplateName::SubstTemplateTemplateParm: {
4054 SubstTemplateTemplateParmStorage *subst
4055 = Name.getAsSubstTemplateTemplateParm();
4056 return getCanonicalTemplateName(subst->getReplacement());
4057 }
4058
4059 case TemplateName::SubstTemplateTemplateParmPack: {
4060 SubstTemplateTemplateParmPackStorage *subst
4061 = Name.getAsSubstTemplateTemplateParmPack();
4062 TemplateTemplateParmDecl *canonParameter
4063 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4064 TemplateArgument canonArgPack
4065 = getCanonicalTemplateArgument(subst->getArgumentPack());
4066 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4067 }
4068 }
4069
4070 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004071}
4072
Douglas Gregoradee3e32009-11-11 23:06:43 +00004073bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4074 X = getCanonicalTemplateName(X);
4075 Y = getCanonicalTemplateName(Y);
4076 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4077}
4078
Mike Stump11289f42009-09-09 15:08:12 +00004079TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004080ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004081 switch (Arg.getKind()) {
4082 case TemplateArgument::Null:
4083 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004084
Douglas Gregora8e02e72009-07-28 23:00:59 +00004085 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004086 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004087
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004088 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004089 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4090 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004091 }
Mike Stump11289f42009-09-09 15:08:12 +00004092
Eli Friedmanb826a002012-09-26 02:36:12 +00004093 case TemplateArgument::NullPtr:
4094 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4095 /*isNullPtr*/true);
4096
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004097 case TemplateArgument::Template:
4098 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004099
4100 case TemplateArgument::TemplateExpansion:
4101 return TemplateArgument(getCanonicalTemplateName(
4102 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004103 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004104
Douglas Gregora8e02e72009-07-28 23:00:59 +00004105 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004106 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004107
Douglas Gregora8e02e72009-07-28 23:00:59 +00004108 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004109 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004110
Douglas Gregora8e02e72009-07-28 23:00:59 +00004111 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004112 if (Arg.pack_size() == 0)
4113 return Arg;
4114
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004115 TemplateArgument *CanonArgs
4116 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004117 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004118 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004119 AEnd = Arg.pack_end();
4120 A != AEnd; (void)++A, ++Idx)
4121 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004122
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004123 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004124 }
4125 }
4126
4127 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004128 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004129}
4130
Douglas Gregor333489b2009-03-27 23:10:48 +00004131NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004132ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004133 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004134 return 0;
4135
4136 switch (NNS->getKind()) {
4137 case NestedNameSpecifier::Identifier:
4138 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004139 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004140 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4141 NNS->getAsIdentifier());
4142
4143 case NestedNameSpecifier::Namespace:
4144 // A namespace is canonical; build a nested-name-specifier with
4145 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004146 return NestedNameSpecifier::Create(*this, 0,
4147 NNS->getAsNamespace()->getOriginalNamespace());
4148
4149 case NestedNameSpecifier::NamespaceAlias:
4150 // A namespace is canonical; build a nested-name-specifier with
4151 // this namespace and no prefix.
4152 return NestedNameSpecifier::Create(*this, 0,
4153 NNS->getAsNamespaceAlias()->getNamespace()
4154 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004155
4156 case NestedNameSpecifier::TypeSpec:
4157 case NestedNameSpecifier::TypeSpecWithTemplate: {
4158 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004159
4160 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4161 // break it apart into its prefix and identifier, then reconsititute those
4162 // as the canonical nested-name-specifier. This is required to canonicalize
4163 // a dependent nested-name-specifier involving typedefs of dependent-name
4164 // types, e.g.,
4165 // typedef typename T::type T1;
4166 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004167 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4168 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004169 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004170
Eli Friedman5358a0a2012-03-03 04:09:56 +00004171 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4172 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4173 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004174 return NestedNameSpecifier::Create(*this, 0, false,
4175 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004176 }
4177
4178 case NestedNameSpecifier::Global:
4179 // The global specifier is canonical and unique.
4180 return NNS;
4181 }
4182
David Blaikie8a40f702012-01-17 06:56:22 +00004183 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004184}
4185
Chris Lattner7adf0762008-08-04 07:31:14 +00004186
Jay Foad39c79802011-01-12 09:06:06 +00004187const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004188 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004189 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004190 // Handle the common positive case fast.
4191 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4192 return AT;
4193 }
Mike Stump11289f42009-09-09 15:08:12 +00004194
John McCall8ccfcb52009-09-24 19:53:00 +00004195 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004196 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004197 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004198
John McCall8ccfcb52009-09-24 19:53:00 +00004199 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004200 // implements C99 6.7.3p8: "If the specification of an array type includes
4201 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004202
Chris Lattner7adf0762008-08-04 07:31:14 +00004203 // If we get here, we either have type qualifiers on the type, or we have
4204 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004205 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004206
John McCall33ddac02011-01-19 10:06:00 +00004207 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004208 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004209
Chris Lattner7adf0762008-08-04 07:31:14 +00004210 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004211 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004212 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004213 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004214
Chris Lattner7adf0762008-08-04 07:31:14 +00004215 // Otherwise, we have an array and we have qualifiers on it. Push the
4216 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004217 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004218
Chris Lattner7adf0762008-08-04 07:31:14 +00004219 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4220 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4221 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004222 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004223 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4224 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4225 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004226 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004227
Mike Stump11289f42009-09-09 15:08:12 +00004228 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004229 = dyn_cast<DependentSizedArrayType>(ATy))
4230 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004231 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004232 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004233 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004234 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004235 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004236
Chris Lattner7adf0762008-08-04 07:31:14 +00004237 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004238 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004239 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004240 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004241 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004242 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004243}
4244
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004245QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004246 if (T->isArrayType() || T->isFunctionType())
4247 return getDecayedType(T);
4248 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004249}
4250
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004251QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004252 T = getVariableArrayDecayedType(T);
4253 T = getAdjustedParameterType(T);
4254 return T.getUnqualifiedType();
4255}
4256
Chris Lattnera21ad802008-04-02 05:18:44 +00004257/// getArrayDecayedType - Return the properly qualified result of decaying the
4258/// specified array type to a pointer. This operation is non-trivial when
4259/// handling typedefs etc. The canonical type of "T" must be an array type,
4260/// this returns a pointer to a properly qualified element of the array.
4261///
4262/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004263QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004264 // Get the element type with 'getAsArrayType' so that we don't lose any
4265 // typedefs in the element type of the array. This also handles propagation
4266 // of type qualifiers from the array type into the element type if present
4267 // (C99 6.7.3p8).
4268 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4269 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004270
Chris Lattner7adf0762008-08-04 07:31:14 +00004271 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004272
4273 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004274 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004275}
4276
John McCall33ddac02011-01-19 10:06:00 +00004277QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4278 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004279}
4280
John McCall33ddac02011-01-19 10:06:00 +00004281QualType ASTContext::getBaseElementType(QualType type) const {
4282 Qualifiers qs;
4283 while (true) {
4284 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004285 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004286 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004287
John McCall33ddac02011-01-19 10:06:00 +00004288 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004289 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004290 }
Mike Stump11289f42009-09-09 15:08:12 +00004291
John McCall33ddac02011-01-19 10:06:00 +00004292 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004293}
4294
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004295/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004296uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004297ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4298 uint64_t ElementCount = 1;
4299 do {
4300 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004301 CA = dyn_cast_or_null<ConstantArrayType>(
4302 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004303 } while (CA);
4304 return ElementCount;
4305}
4306
Steve Naroff0af91202007-04-27 21:51:21 +00004307/// getFloatingRank - Return a relative rank for floating point types.
4308/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004309static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004310 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004311 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004312
John McCall9dd450b2009-09-21 23:43:11 +00004313 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4314 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004315 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004316 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004317 case BuiltinType::Float: return FloatRank;
4318 case BuiltinType::Double: return DoubleRank;
4319 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004320 }
4321}
4322
Mike Stump11289f42009-09-09 15:08:12 +00004323/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4324/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004325/// 'typeDomain' is a real floating point or complex type.
4326/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004327QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4328 QualType Domain) const {
4329 FloatingRank EltRank = getFloatingRank(Size);
4330 if (Domain->isComplexType()) {
4331 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004332 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004333 case FloatRank: return FloatComplexTy;
4334 case DoubleRank: return DoubleComplexTy;
4335 case LongDoubleRank: return LongDoubleComplexTy;
4336 }
Steve Naroff0af91202007-04-27 21:51:21 +00004337 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004338
4339 assert(Domain->isRealFloatingType() && "Unknown domain!");
4340 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004341 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004342 case FloatRank: return FloatTy;
4343 case DoubleRank: return DoubleTy;
4344 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004345 }
David Blaikief47fa302012-01-17 02:30:50 +00004346 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004347}
4348
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004349/// getFloatingTypeOrder - Compare the rank of the two specified floating
4350/// point types, ignoring the domain of the type (i.e. 'double' ==
4351/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004352/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004353int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004354 FloatingRank LHSR = getFloatingRank(LHS);
4355 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004356
Chris Lattnerb90739d2008-04-06 23:38:49 +00004357 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004358 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004359 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004360 return 1;
4361 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004362}
4363
Chris Lattner76a00cf2008-04-06 22:59:24 +00004364/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4365/// routine will assert if passed a built-in type that isn't an integer or enum,
4366/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004367unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004368 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004369
Chris Lattner76a00cf2008-04-06 22:59:24 +00004370 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004371 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004372 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004373 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004374 case BuiltinType::Char_S:
4375 case BuiltinType::Char_U:
4376 case BuiltinType::SChar:
4377 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004378 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004379 case BuiltinType::Short:
4380 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004381 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004382 case BuiltinType::Int:
4383 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004384 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004385 case BuiltinType::Long:
4386 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004387 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004388 case BuiltinType::LongLong:
4389 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004390 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004391 case BuiltinType::Int128:
4392 case BuiltinType::UInt128:
4393 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004394 }
4395}
4396
Eli Friedman629ffb92009-08-20 04:21:42 +00004397/// \brief Whether this is a promotable bitfield reference according
4398/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4399///
4400/// \returns the type this bit-field will promote to, or NULL if no
4401/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004402QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004403 if (E->isTypeDependent() || E->isValueDependent())
4404 return QualType();
4405
John McCalld25db7e2013-05-06 21:39:12 +00004406 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004407 if (!Field)
4408 return QualType();
4409
4410 QualType FT = Field->getType();
4411
Richard Smithcaf33902011-10-10 18:28:20 +00004412 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004413 uint64_t IntSize = getTypeSize(IntTy);
4414 // GCC extension compatibility: if the bit-field size is less than or equal
4415 // to the size of int, it gets promoted no matter what its type is.
4416 // For instance, unsigned long bf : 4 gets promoted to signed int.
4417 if (BitWidth < IntSize)
4418 return IntTy;
4419
4420 if (BitWidth == IntSize)
4421 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4422
4423 // Types bigger than int are not subject to promotions, and therefore act
4424 // like the base type.
4425 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4426 // is ridiculous.
4427 return QualType();
4428}
4429
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004430/// getPromotedIntegerType - Returns the type that Promotable will
4431/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4432/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004433QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004434 assert(!Promotable.isNull());
4435 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004436 if (const EnumType *ET = Promotable->getAs<EnumType>())
4437 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004438
4439 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4440 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4441 // (3.9.1) can be converted to a prvalue of the first of the following
4442 // types that can represent all the values of its underlying type:
4443 // int, unsigned int, long int, unsigned long int, long long int, or
4444 // unsigned long long int [...]
4445 // FIXME: Is there some better way to compute this?
4446 if (BT->getKind() == BuiltinType::WChar_S ||
4447 BT->getKind() == BuiltinType::WChar_U ||
4448 BT->getKind() == BuiltinType::Char16 ||
4449 BT->getKind() == BuiltinType::Char32) {
4450 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4451 uint64_t FromSize = getTypeSize(BT);
4452 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4453 LongLongTy, UnsignedLongLongTy };
4454 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4455 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4456 if (FromSize < ToSize ||
4457 (FromSize == ToSize &&
4458 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4459 return PromoteTypes[Idx];
4460 }
4461 llvm_unreachable("char type should fit into long long");
4462 }
4463 }
4464
4465 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004466 if (Promotable->isSignedIntegerType())
4467 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004468 uint64_t PromotableSize = getIntWidth(Promotable);
4469 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004470 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4471 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4472}
4473
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004474/// \brief Recurses in pointer/array types until it finds an objc retainable
4475/// type and returns its ownership.
4476Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4477 while (!T.isNull()) {
4478 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4479 return T.getObjCLifetime();
4480 if (T->isArrayType())
4481 T = getBaseElementType(T);
4482 else if (const PointerType *PT = T->getAs<PointerType>())
4483 T = PT->getPointeeType();
4484 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004485 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004486 else
4487 break;
4488 }
4489
4490 return Qualifiers::OCL_None;
4491}
4492
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004493static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4494 // Incomplete enum types are not treated as integer types.
4495 // FIXME: In C++, enum types are never integer types.
4496 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4497 return ET->getDecl()->getIntegerType().getTypePtr();
4498 return NULL;
4499}
4500
Mike Stump11289f42009-09-09 15:08:12 +00004501/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004502/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004503/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004504int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004505 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4506 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004507
4508 // Unwrap enums to their underlying type.
4509 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4510 LHSC = getIntegerTypeForEnum(ET);
4511 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4512 RHSC = getIntegerTypeForEnum(ET);
4513
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004514 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004515
Chris Lattner76a00cf2008-04-06 22:59:24 +00004516 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4517 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004518
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004519 unsigned LHSRank = getIntegerRank(LHSC);
4520 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004521
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004522 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4523 if (LHSRank == RHSRank) return 0;
4524 return LHSRank > RHSRank ? 1 : -1;
4525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004527 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4528 if (LHSUnsigned) {
4529 // If the unsigned [LHS] type is larger, return it.
4530 if (LHSRank >= RHSRank)
4531 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004532
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004533 // If the signed type can represent all values of the unsigned type, it
4534 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004535 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004536 return -1;
4537 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004538
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004539 // If the unsigned [RHS] type is larger, return it.
4540 if (RHSRank >= LHSRank)
4541 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004542
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004543 // If the signed type can represent all values of the unsigned type, it
4544 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004545 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004546 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004547}
Anders Carlsson98f07902007-08-17 05:31:46 +00004548
Mike Stump11289f42009-09-09 15:08:12 +00004549// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004550QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004551 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004552 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004553 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004554
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004555 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004556
Anders Carlsson98f07902007-08-17 05:31:46 +00004557 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004558 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004559 // int flags;
4560 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004561 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004562 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004563 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004564 FieldTypes[3] = LongTy;
4565
Anders Carlsson98f07902007-08-17 05:31:46 +00004566 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004567 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004568 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004569 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004570 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004571 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004572 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004573 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004574 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004575 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004576 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004577 }
4578
Douglas Gregord5058122010-02-11 01:19:42 +00004579 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004580 }
Mike Stump11289f42009-09-09 15:08:12 +00004581
Anders Carlsson98f07902007-08-17 05:31:46 +00004582 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004583}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004584
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004585QualType ASTContext::getObjCSuperType() const {
4586 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004587 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004588 TUDecl->addDecl(ObjCSuperTypeDecl);
4589 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4590 }
4591 return ObjCSuperType;
4592}
4593
Douglas Gregor512b0772009-04-23 22:29:11 +00004594void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004595 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004596 assert(Rec && "Invalid CFConstantStringType");
4597 CFConstantStringTypeDecl = Rec->getDecl();
4598}
4599
Jay Foad39c79802011-01-12 09:06:06 +00004600QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004601 if (BlockDescriptorType)
4602 return getTagDeclType(BlockDescriptorType);
4603
Alp Toker2dea15b2013-12-17 01:22:38 +00004604 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004605 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004606 RD = buildImplicitRecord("__block_descriptor");
4607 RD->startDefinition();
4608
Mike Stumpd0153282009-10-20 02:12:22 +00004609 QualType FieldTypes[] = {
4610 UnsignedLongTy,
4611 UnsignedLongTy,
4612 };
4613
Craig Topperd6d31ac2013-07-15 08:24:27 +00004614 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004615 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004616 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004617 };
4618
4619 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004620 FieldDecl *Field = FieldDecl::Create(
4621 *this, RD, SourceLocation(), SourceLocation(),
4622 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4623 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004624 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004625 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004626 }
4627
Alp Toker2dea15b2013-12-17 01:22:38 +00004628 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004629
Alp Toker2dea15b2013-12-17 01:22:38 +00004630 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004631
4632 return getTagDeclType(BlockDescriptorType);
4633}
4634
Jay Foad39c79802011-01-12 09:06:06 +00004635QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004636 if (BlockDescriptorExtendedType)
4637 return getTagDeclType(BlockDescriptorExtendedType);
4638
Alp Toker2dea15b2013-12-17 01:22:38 +00004639 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004640 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004641 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4642 RD->startDefinition();
4643
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004644 QualType FieldTypes[] = {
4645 UnsignedLongTy,
4646 UnsignedLongTy,
4647 getPointerType(VoidPtrTy),
4648 getPointerType(VoidPtrTy)
4649 };
4650
Craig Topperd6d31ac2013-07-15 08:24:27 +00004651 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004652 "reserved",
4653 "Size",
4654 "CopyFuncPtr",
4655 "DestroyFuncPtr"
4656 };
4657
4658 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004659 FieldDecl *Field = FieldDecl::Create(
4660 *this, RD, SourceLocation(), SourceLocation(),
4661 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4662 /*BitWidth=*/0,
4663 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004664 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004665 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004666 }
4667
Alp Toker2dea15b2013-12-17 01:22:38 +00004668 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004669
Alp Toker2dea15b2013-12-17 01:22:38 +00004670 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004671 return getTagDeclType(BlockDescriptorExtendedType);
4672}
4673
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004674/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4675/// requires copy/dispose. Note that this must match the logic
4676/// in buildByrefHelpers.
4677bool ASTContext::BlockRequiresCopying(QualType Ty,
4678 const VarDecl *D) {
4679 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4680 const Expr *copyExpr = getBlockVarCopyInits(D);
4681 if (!copyExpr && record->hasTrivialDestructor()) return false;
4682
Mike Stump94967902009-10-21 18:16:27 +00004683 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004684 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004685
4686 if (!Ty->isObjCRetainableType()) return false;
4687
4688 Qualifiers qs = Ty.getQualifiers();
4689
4690 // If we have lifetime, that dominates.
4691 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4692 assert(getLangOpts().ObjCAutoRefCount);
4693
4694 switch (lifetime) {
4695 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4696
4697 // These are just bits as far as the runtime is concerned.
4698 case Qualifiers::OCL_ExplicitNone:
4699 case Qualifiers::OCL_Autoreleasing:
4700 return false;
4701
4702 // Tell the runtime that this is ARC __weak, called by the
4703 // byref routines.
4704 case Qualifiers::OCL_Weak:
4705 // ARC __strong __block variables need to be retained.
4706 case Qualifiers::OCL_Strong:
4707 return true;
4708 }
4709 llvm_unreachable("fell out of lifetime switch!");
4710 }
4711 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4712 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004713}
4714
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004715bool ASTContext::getByrefLifetime(QualType Ty,
4716 Qualifiers::ObjCLifetime &LifeTime,
4717 bool &HasByrefExtendedLayout) const {
4718
4719 if (!getLangOpts().ObjC1 ||
4720 getLangOpts().getGC() != LangOptions::NonGC)
4721 return false;
4722
4723 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004724 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004725 HasByrefExtendedLayout = true;
4726 LifeTime = Qualifiers::OCL_None;
4727 }
4728 else if (getLangOpts().ObjCAutoRefCount)
4729 LifeTime = Ty.getObjCLifetime();
4730 // MRR.
4731 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4732 LifeTime = Qualifiers::OCL_ExplicitNone;
4733 else
4734 LifeTime = Qualifiers::OCL_None;
4735 return true;
4736}
4737
Douglas Gregorbab8a962011-09-08 01:46:34 +00004738TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4739 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004740 ObjCInstanceTypeDecl =
4741 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004742 return ObjCInstanceTypeDecl;
4743}
4744
Anders Carlsson18acd442007-10-29 06:33:42 +00004745// This returns true if a type has been typedefed to BOOL:
4746// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004747static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004748 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004749 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4750 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004751
Anders Carlssond8499822007-10-29 05:01:08 +00004752 return false;
4753}
4754
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004755/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004756/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004757CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004758 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4759 return CharUnits::Zero();
4760
Ken Dyck40775002010-01-11 17:06:35 +00004761 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004762
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004763 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004764 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004765 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004766 // Treat arrays as pointers, since that's how they're passed in.
4767 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004768 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004769 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004770}
4771
4772static inline
4773std::string charUnitsToString(const CharUnits &CU) {
4774 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004775}
4776
John McCall351762c2011-02-07 10:33:21 +00004777/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004778/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004779std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4780 std::string S;
4781
David Chisnall950a9512009-11-17 19:33:30 +00004782 const BlockDecl *Decl = Expr->getBlockDecl();
4783 QualType BlockTy =
4784 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4785 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004786 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004787 getObjCEncodingForMethodParameter(
4788 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4789 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004790 else
Alp Toker314cc812014-01-25 16:55:45 +00004791 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004792 // Compute size of all parameters.
4793 // Start with computing size of a pointer in number of bytes.
4794 // FIXME: There might(should) be a better way of doing this computation!
4795 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004796 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4797 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004798 for (auto PI : Decl->params()) {
4799 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004800 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004801 if (sz.isZero())
4802 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004803 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004804 ParmOffset += sz;
4805 }
4806 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004807 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004808 // Block pointer and offset.
4809 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004810
4811 // Argument types.
4812 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004813 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004814 QualType PType = PVDecl->getOriginalType();
4815 if (const ArrayType *AT =
4816 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4817 // Use array's original type only if it has known number of
4818 // elements.
4819 if (!isa<ConstantArrayType>(AT))
4820 PType = PVDecl->getType();
4821 } else if (PType->isFunctionType())
4822 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004823 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004824 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4825 S, true /*Extended*/);
4826 else
4827 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004828 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004829 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004830 }
John McCall351762c2011-02-07 10:33:21 +00004831
4832 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004833}
4834
Douglas Gregora9d84932011-05-27 01:19:52 +00004835bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004836 std::string& S) {
4837 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004838 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004839 CharUnits ParmOffset;
4840 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004841 for (auto PI : Decl->params()) {
4842 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004843 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004844 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004845 continue;
4846
David Chisnall50e4eba2010-12-30 14:05:53 +00004847 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004848 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004849 ParmOffset += sz;
4850 }
4851 S += charUnitsToString(ParmOffset);
4852 ParmOffset = CharUnits::Zero();
4853
4854 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004855 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004856 QualType PType = PVDecl->getOriginalType();
4857 if (const ArrayType *AT =
4858 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4859 // Use array's original type only if it has known number of
4860 // elements.
4861 if (!isa<ConstantArrayType>(AT))
4862 PType = PVDecl->getType();
4863 } else if (PType->isFunctionType())
4864 PType = PVDecl->getType();
4865 getObjCEncodingForType(PType, S);
4866 S += charUnitsToString(ParmOffset);
4867 ParmOffset += getObjCEncodingTypeSize(PType);
4868 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004869
4870 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004871}
4872
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004873/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4874/// method parameter or return type. If Extended, include class names and
4875/// block object types.
4876void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4877 QualType T, std::string& S,
4878 bool Extended) const {
4879 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4880 getObjCEncodingForTypeQualifier(QT, S);
4881 // Encode parameter type.
4882 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4883 true /*OutermostType*/,
4884 false /*EncodingProperty*/,
4885 false /*StructField*/,
4886 Extended /*EncodeBlockParameters*/,
4887 Extended /*EncodeClassNames*/);
4888}
4889
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004890/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004891/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004892bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004893 std::string& S,
4894 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004895 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004896 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004897 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4898 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004899 // Compute size of all parameters.
4900 // Start with computing size of a pointer in number of bytes.
4901 // FIXME: There might(should) be a better way of doing this computation!
4902 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004903 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004904 // The first two arguments (self and _cmd) are pointers; account for
4905 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004906 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004907 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004908 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004909 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004910 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004911 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004912 continue;
4913
Ken Dyck40775002010-01-11 17:06:35 +00004914 assert (sz.isPositive() &&
4915 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004916 ParmOffset += sz;
4917 }
Ken Dyck40775002010-01-11 17:06:35 +00004918 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004919 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004920 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004921
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004922 // Argument types.
4923 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004924 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004925 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004926 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004927 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004928 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004929 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4930 // Use array's original type only if it has known number of
4931 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004932 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004933 PType = PVDecl->getType();
4934 } else if (PType->isFunctionType())
4935 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004936 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4937 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004938 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004939 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004940 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004941
4942 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004943}
4944
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004945ObjCPropertyImplDecl *
4946ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4947 const ObjCPropertyDecl *PD,
4948 const Decl *Container) const {
4949 if (!Container)
4950 return 0;
4951 if (const ObjCCategoryImplDecl *CID =
4952 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4953 for (ObjCCategoryImplDecl::propimpl_iterator
4954 i = CID->propimpl_begin(), e = CID->propimpl_end();
4955 i != e; ++i) {
4956 ObjCPropertyImplDecl *PID = *i;
4957 if (PID->getPropertyDecl() == PD)
4958 return PID;
4959 }
4960 } else {
4961 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4962 for (ObjCCategoryImplDecl::propimpl_iterator
4963 i = OID->propimpl_begin(), e = OID->propimpl_end();
4964 i != e; ++i) {
4965 ObjCPropertyImplDecl *PID = *i;
4966 if (PID->getPropertyDecl() == PD)
4967 return PID;
4968 }
4969 }
4970 return 0;
4971}
4972
Daniel Dunbar4932b362008-08-28 04:38:10 +00004973/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004974/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004975/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4976/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004977/// Property attributes are stored as a comma-delimited C string. The simple
4978/// attributes readonly and bycopy are encoded as single characters. The
4979/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4980/// encoded as single characters, followed by an identifier. Property types
4981/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004982/// these attributes are defined by the following enumeration:
4983/// @code
4984/// enum PropertyAttributes {
4985/// kPropertyReadOnly = 'R', // property is read-only.
4986/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4987/// kPropertyByref = '&', // property is a reference to the value last assigned
4988/// kPropertyDynamic = 'D', // property is dynamic
4989/// kPropertyGetter = 'G', // followed by getter selector name
4990/// kPropertySetter = 'S', // followed by setter selector name
4991/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004992/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004993/// kPropertyWeak = 'W' // 'weak' property
4994/// kPropertyStrong = 'P' // property GC'able
4995/// kPropertyNonAtomic = 'N' // property non-atomic
4996/// };
4997/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004998void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004999 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005000 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005001 // Collect information from the property implementation decl(s).
5002 bool Dynamic = false;
5003 ObjCPropertyImplDecl *SynthesizePID = 0;
5004
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005005 if (ObjCPropertyImplDecl *PropertyImpDecl =
5006 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5007 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5008 Dynamic = true;
5009 else
5010 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005011 }
5012
5013 // FIXME: This is not very efficient.
5014 S = "T";
5015
5016 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005017 // GCC has some special rules regarding encoding of properties which
5018 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005019 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005020 true /* outermost type */,
5021 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005022
5023 if (PD->isReadOnly()) {
5024 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005025 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5026 S += ",C";
5027 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5028 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005029 } else {
5030 switch (PD->getSetterKind()) {
5031 case ObjCPropertyDecl::Assign: break;
5032 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005033 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005034 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005035 }
5036 }
5037
5038 // It really isn't clear at all what this means, since properties
5039 // are "dynamic by default".
5040 if (Dynamic)
5041 S += ",D";
5042
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005043 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5044 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005045
Daniel Dunbar4932b362008-08-28 04:38:10 +00005046 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5047 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005048 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005049 }
5050
5051 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5052 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005053 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005054 }
5055
5056 if (SynthesizePID) {
5057 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5058 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005059 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005060 }
5061
5062 // FIXME: OBJCGC: weak & strong
5063}
5064
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005065/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005066/// Another legacy compatibility encoding: 32-bit longs are encoded as
5067/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005068/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5069///
5070void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005071 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005072 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005073 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005074 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005075 else
Jay Foad39c79802011-01-12 09:06:06 +00005076 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005077 PointeeTy = IntTy;
5078 }
5079 }
5080}
5081
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005082void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005083 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005084 // We follow the behavior of gcc, expanding structures which are
5085 // directly pointed to, and expanding embedded structures. Note that
5086 // these rules are sufficient to prevent recursive encoding of the
5087 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005088 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005089 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005090}
5091
John McCall393a78d2012-12-20 02:45:14 +00005092static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5093 BuiltinType::Kind kind) {
5094 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005095 case BuiltinType::Void: return 'v';
5096 case BuiltinType::Bool: return 'B';
5097 case BuiltinType::Char_U:
5098 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005099 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005100 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005101 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005102 case BuiltinType::UInt: return 'I';
5103 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005104 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005105 case BuiltinType::UInt128: return 'T';
5106 case BuiltinType::ULongLong: return 'Q';
5107 case BuiltinType::Char_S:
5108 case BuiltinType::SChar: return 'c';
5109 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005110 case BuiltinType::WChar_S:
5111 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005112 case BuiltinType::Int: return 'i';
5113 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005114 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005115 case BuiltinType::LongLong: return 'q';
5116 case BuiltinType::Int128: return 't';
5117 case BuiltinType::Float: return 'f';
5118 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005119 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005120 case BuiltinType::NullPtr: return '*'; // like char*
5121
5122 case BuiltinType::Half:
5123 // FIXME: potentially need @encodes for these!
5124 return ' ';
5125
5126 case BuiltinType::ObjCId:
5127 case BuiltinType::ObjCClass:
5128 case BuiltinType::ObjCSel:
5129 llvm_unreachable("@encoding ObjC primitive type");
5130
5131 // OpenCL and placeholder types don't need @encodings.
5132 case BuiltinType::OCLImage1d:
5133 case BuiltinType::OCLImage1dArray:
5134 case BuiltinType::OCLImage1dBuffer:
5135 case BuiltinType::OCLImage2d:
5136 case BuiltinType::OCLImage2dArray:
5137 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005138 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005139 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005140 case BuiltinType::Dependent:
5141#define BUILTIN_TYPE(KIND, ID)
5142#define PLACEHOLDER_TYPE(KIND, ID) \
5143 case BuiltinType::KIND:
5144#include "clang/AST/BuiltinTypes.def"
5145 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005146 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005147 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005148}
5149
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005150static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5151 EnumDecl *Enum = ET->getDecl();
5152
5153 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5154 if (!Enum->isFixed())
5155 return 'i';
5156
5157 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005158 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5159 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005160}
5161
Jay Foad39c79802011-01-12 09:06:06 +00005162static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005163 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005164 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005165 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005166 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5167 // The GNU runtime requires more information; bitfields are encoded as b,
5168 // then the offset (in bits) of the first element, then the type of the
5169 // bitfield, then the size in bits. For example, in this structure:
5170 //
5171 // struct
5172 // {
5173 // int integer;
5174 // int flags:2;
5175 // };
5176 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5177 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5178 // information is not especially sensible, but we're stuck with it for
5179 // compatibility with GCC, although providing it breaks anything that
5180 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005181 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005182 const RecordDecl *RD = FD->getParent();
5183 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005184 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005185 if (const EnumType *ET = T->getAs<EnumType>())
5186 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005187 else {
5188 const BuiltinType *BT = T->castAs<BuiltinType>();
5189 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5190 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005191 }
Richard Smithcaf33902011-10-10 18:28:20 +00005192 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005193}
5194
Daniel Dunbar07d07852009-10-18 21:17:35 +00005195// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005196void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5197 bool ExpandPointedToStructures,
5198 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005199 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005200 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005201 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005202 bool StructField,
5203 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005204 bool EncodeClassNames,
5205 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005206 CanQualType CT = getCanonicalType(T);
5207 switch (CT->getTypeClass()) {
5208 case Type::Builtin:
5209 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005210 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005211 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005212 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5213 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5214 else
5215 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005216 return;
Mike Stump11289f42009-09-09 15:08:12 +00005217
John McCall393a78d2012-12-20 02:45:14 +00005218 case Type::Complex: {
5219 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005220 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005221 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005222 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005223 return;
5224 }
John McCall393a78d2012-12-20 02:45:14 +00005225
5226 case Type::Atomic: {
5227 const AtomicType *AT = T->castAs<AtomicType>();
5228 S += 'A';
5229 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5230 false, false);
5231 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005232 }
John McCall393a78d2012-12-20 02:45:14 +00005233
5234 // encoding for pointer or reference types.
5235 case Type::Pointer:
5236 case Type::LValueReference:
5237 case Type::RValueReference: {
5238 QualType PointeeTy;
5239 if (isa<PointerType>(CT)) {
5240 const PointerType *PT = T->castAs<PointerType>();
5241 if (PT->isObjCSelType()) {
5242 S += ':';
5243 return;
5244 }
5245 PointeeTy = PT->getPointeeType();
5246 } else {
5247 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5248 }
5249
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005250 bool isReadOnly = false;
5251 // For historical/compatibility reasons, the read-only qualifier of the
5252 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5253 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005254 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005255 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005256 if (OutermostType && T.isConstQualified()) {
5257 isReadOnly = true;
5258 S += 'r';
5259 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005260 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005261 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005262 while (P->getAs<PointerType>())
5263 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005264 if (P.isConstQualified()) {
5265 isReadOnly = true;
5266 S += 'r';
5267 }
5268 }
5269 if (isReadOnly) {
5270 // Another legacy compatibility encoding. Some ObjC qualifier and type
5271 // combinations need to be rearranged.
5272 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005273 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005274 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005275 }
Mike Stump11289f42009-09-09 15:08:12 +00005276
Anders Carlssond8499822007-10-29 05:01:08 +00005277 if (PointeeTy->isCharType()) {
5278 // char pointer types should be encoded as '*' unless it is a
5279 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005280 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005281 S += '*';
5282 return;
5283 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005284 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005285 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5286 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5287 S += '#';
5288 return;
5289 }
5290 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5291 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5292 S += '@';
5293 return;
5294 }
5295 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005296 }
Anders Carlssond8499822007-10-29 05:01:08 +00005297 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005298 getLegacyIntegralTypeEncoding(PointeeTy);
5299
Mike Stump11289f42009-09-09 15:08:12 +00005300 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005301 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005302 return;
5303 }
John McCall393a78d2012-12-20 02:45:14 +00005304
5305 case Type::ConstantArray:
5306 case Type::IncompleteArray:
5307 case Type::VariableArray: {
5308 const ArrayType *AT = cast<ArrayType>(CT);
5309
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005310 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005311 // Incomplete arrays are encoded as a pointer to the array element.
5312 S += '^';
5313
Mike Stump11289f42009-09-09 15:08:12 +00005314 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005315 false, ExpandStructures, FD);
5316 } else {
5317 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005318
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005319 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5320 S += llvm::utostr(CAT->getSize().getZExtValue());
5321 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005322 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005323 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5324 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005325 S += '0';
5326 }
Mike Stump11289f42009-09-09 15:08:12 +00005327
5328 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005329 false, ExpandStructures, FD);
5330 S += ']';
5331 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005332 return;
5333 }
Mike Stump11289f42009-09-09 15:08:12 +00005334
John McCall393a78d2012-12-20 02:45:14 +00005335 case Type::FunctionNoProto:
5336 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005337 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005338 return;
Mike Stump11289f42009-09-09 15:08:12 +00005339
John McCall393a78d2012-12-20 02:45:14 +00005340 case Type::Record: {
5341 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005342 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005343 // Anonymous structures print as '?'
5344 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5345 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005346 if (ClassTemplateSpecializationDecl *Spec
5347 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5348 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005349 llvm::raw_string_ostream OS(S);
5350 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005351 TemplateArgs.data(),
5352 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005353 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005354 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005355 } else {
5356 S += '?';
5357 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005358 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005359 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005360 if (!RDecl->isUnion()) {
5361 getObjCEncodingForStructureImpl(RDecl, S, FD);
5362 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005363 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005364 if (FD) {
5365 S += '"';
5366 S += Field->getNameAsString();
5367 S += '"';
5368 }
Mike Stump11289f42009-09-09 15:08:12 +00005369
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005370 // Special case bit-fields.
5371 if (Field->isBitField()) {
5372 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005373 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005374 } else {
5375 QualType qt = Field->getType();
5376 getLegacyIntegralTypeEncoding(qt);
5377 getObjCEncodingForTypeImpl(qt, S, false, true,
5378 FD, /*OutermostType*/false,
5379 /*EncodingProperty*/false,
5380 /*StructField*/true);
5381 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005382 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005383 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005384 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005385 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005386 return;
5387 }
Mike Stump11289f42009-09-09 15:08:12 +00005388
John McCall393a78d2012-12-20 02:45:14 +00005389 case Type::BlockPointer: {
5390 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005391 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005392 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005393 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005394
5395 S += '<';
5396 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005397 getObjCEncodingForTypeImpl(
5398 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5399 FD, false /* OutermostType */, EncodingProperty,
5400 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005401 // Block self
5402 S += "@?";
5403 // Block parameters
5404 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005405 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5406 E = FPT->param_type_end();
5407 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005408 getObjCEncodingForTypeImpl(*I, S,
5409 ExpandPointedToStructures,
5410 ExpandStructures,
5411 FD,
5412 false /* OutermostType */,
5413 EncodingProperty,
5414 false /* StructField */,
5415 EncodeBlockParameters,
5416 EncodeClassNames);
5417 }
5418 }
5419 S += '>';
5420 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005421 return;
5422 }
Mike Stump11289f42009-09-09 15:08:12 +00005423
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005424 case Type::ObjCObject: {
5425 // hack to match legacy encoding of *id and *Class
5426 QualType Ty = getObjCObjectPointerType(CT);
5427 if (Ty->isObjCIdType()) {
5428 S += "{objc_object=}";
5429 return;
5430 }
5431 else if (Ty->isObjCClassType()) {
5432 S += "{objc_class=}";
5433 return;
5434 }
5435 }
5436
John McCall393a78d2012-12-20 02:45:14 +00005437 case Type::ObjCInterface: {
5438 // Ignore protocol qualifiers when mangling at this level.
5439 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005440
John McCall393a78d2012-12-20 02:45:14 +00005441 // The assumption seems to be that this assert will succeed
5442 // because nested levels will have filtered out 'id' and 'Class'.
5443 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005444 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005445 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005446 S += '{';
5447 const IdentifierInfo *II = OI->getIdentifier();
5448 S += II->getName();
5449 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005450 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005451 DeepCollectObjCIvars(OI, true, Ivars);
5452 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005453 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005454 if (Field->isBitField())
5455 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005456 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005457 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5458 false, false, false, false, false,
5459 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005460 }
5461 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005462 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005463 }
Mike Stump11289f42009-09-09 15:08:12 +00005464
John McCall393a78d2012-12-20 02:45:14 +00005465 case Type::ObjCObjectPointer: {
5466 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005467 if (OPT->isObjCIdType()) {
5468 S += '@';
5469 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005470 }
Mike Stump11289f42009-09-09 15:08:12 +00005471
Steve Narofff0c86112009-10-28 22:03:49 +00005472 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5473 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5474 // Since this is a binary compatibility issue, need to consult with runtime
5475 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005476 S += '#';
5477 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005478 }
Mike Stump11289f42009-09-09 15:08:12 +00005479
Chris Lattnere7cabb92009-07-13 00:10:46 +00005480 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005481 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005482 ExpandPointedToStructures,
5483 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005484 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005485 // Note that we do extended encoding of protocol qualifer list
5486 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005487 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005488 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5489 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005490 S += '<';
5491 S += (*I)->getNameAsString();
5492 S += '>';
5493 }
5494 S += '"';
5495 }
5496 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005497 }
Mike Stump11289f42009-09-09 15:08:12 +00005498
Chris Lattnere7cabb92009-07-13 00:10:46 +00005499 QualType PointeeTy = OPT->getPointeeType();
5500 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005501 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5502 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005503 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005504 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005505 // {...};
5506 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005507 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005508 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005509 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5510 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5511 DeepCollectObjCIvars(OI, true, Ivars);
5512 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5513 if (cast<FieldDecl>(Ivars[i]) == FD) {
5514 S += '{';
5515 S += OI->getIdentifier()->getName();
5516 S += '}';
5517 return;
5518 }
5519 }
5520 }
Mike Stump11289f42009-09-09 15:08:12 +00005521 getObjCEncodingForTypeImpl(PointeeTy, S,
5522 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005523 NULL,
5524 false, false, false, false, false,
5525 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005526 return;
5527 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005528
5529 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005530 if (OPT->getInterfaceDecl() &&
5531 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005532 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005533 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005534 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5535 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005536 S += '<';
5537 S += (*I)->getNameAsString();
5538 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005539 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005540 S += '"';
5541 }
5542 return;
5543 }
Mike Stump11289f42009-09-09 15:08:12 +00005544
John McCalla9e6e8d2010-05-17 23:56:34 +00005545 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005546 // FIXME: we shoul do better than that. 'M' is available.
5547 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005548 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005549
John McCall393a78d2012-12-20 02:45:14 +00005550 case Type::Vector:
5551 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005552 // This matches gcc's encoding, even though technically it is
5553 // insufficient.
5554 // FIXME. We should do a better job than gcc.
5555 return;
John McCall393a78d2012-12-20 02:45:14 +00005556
Richard Smith27d807c2013-04-30 13:56:41 +00005557 case Type::Auto:
5558 // We could see an undeduced auto type here during error recovery.
5559 // Just ignore it.
5560 return;
5561
John McCall393a78d2012-12-20 02:45:14 +00005562#define ABSTRACT_TYPE(KIND, BASE)
5563#define TYPE(KIND, BASE)
5564#define DEPENDENT_TYPE(KIND, BASE) \
5565 case Type::KIND:
5566#define NON_CANONICAL_TYPE(KIND, BASE) \
5567 case Type::KIND:
5568#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5569 case Type::KIND:
5570#include "clang/AST/TypeNodes.def"
5571 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005572 }
John McCall393a78d2012-12-20 02:45:14 +00005573 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005574}
5575
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005576void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5577 std::string &S,
5578 const FieldDecl *FD,
5579 bool includeVBases) const {
5580 assert(RDecl && "Expected non-null RecordDecl");
5581 assert(!RDecl->isUnion() && "Should not be called for unions");
5582 if (!RDecl->getDefinition())
5583 return;
5584
5585 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5586 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5587 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5588
5589 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005590 for (const auto &BI : CXXRec->bases()) {
5591 if (!BI.isVirtual()) {
5592 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005593 if (base->isEmpty())
5594 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005595 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005596 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5597 std::make_pair(offs, base));
5598 }
5599 }
5600 }
5601
5602 unsigned i = 0;
5603 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5604 FieldEnd = RDecl->field_end();
5605 Field != FieldEnd; ++Field, ++i) {
5606 uint64_t offs = layout.getFieldOffset(i);
5607 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005608 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005609 }
5610
5611 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005612 for (const auto &BI : CXXRec->vbases()) {
5613 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005614 if (base->isEmpty())
5615 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005616 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005617 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5618 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005619 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5620 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005621 }
5622 }
5623
5624 CharUnits size;
5625 if (CXXRec) {
5626 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5627 } else {
5628 size = layout.getSize();
5629 }
5630
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005631#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005632 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005633#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005634 std::multimap<uint64_t, NamedDecl *>::iterator
5635 CurLayObj = FieldOrBaseOffsets.begin();
5636
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005637 if (CXXRec && CXXRec->isDynamicClass() &&
5638 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005639 if (FD) {
5640 S += "\"_vptr$";
5641 std::string recname = CXXRec->getNameAsString();
5642 if (recname.empty()) recname = "?";
5643 S += recname;
5644 S += '"';
5645 }
5646 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005647#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005648 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005649#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005650 }
5651
5652 if (!RDecl->hasFlexibleArrayMember()) {
5653 // Mark the end of the structure.
5654 uint64_t offs = toBits(size);
5655 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5656 std::make_pair(offs, (NamedDecl*)0));
5657 }
5658
5659 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005660#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005661 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005662 if (CurOffs < CurLayObj->first) {
5663 uint64_t padding = CurLayObj->first - CurOffs;
5664 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5665 // packing/alignment of members is different that normal, in which case
5666 // the encoding will be out-of-sync with the real layout.
5667 // If the runtime switches to just consider the size of types without
5668 // taking into account alignment, we could make padding explicit in the
5669 // encoding (e.g. using arrays of chars). The encoding strings would be
5670 // longer then though.
5671 CurOffs += padding;
5672 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005673#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005674
5675 NamedDecl *dcl = CurLayObj->second;
5676 if (dcl == 0)
5677 break; // reached end of structure.
5678
5679 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5680 // We expand the bases without their virtual bases since those are going
5681 // in the initial structure. Note that this differs from gcc which
5682 // expands virtual bases each time one is encountered in the hierarchy,
5683 // making the encoding type bigger than it really is.
5684 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005685 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005686#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005687 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005688#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005689 } else {
5690 FieldDecl *field = cast<FieldDecl>(dcl);
5691 if (FD) {
5692 S += '"';
5693 S += field->getNameAsString();
5694 S += '"';
5695 }
5696
5697 if (field->isBitField()) {
5698 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005699#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005700 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005701#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005702 } else {
5703 QualType qt = field->getType();
5704 getLegacyIntegralTypeEncoding(qt);
5705 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5706 /*OutermostType*/false,
5707 /*EncodingProperty*/false,
5708 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005709#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005710 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005711#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005712 }
5713 }
5714 }
5715}
5716
Mike Stump11289f42009-09-09 15:08:12 +00005717void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005718 std::string& S) const {
5719 if (QT & Decl::OBJC_TQ_In)
5720 S += 'n';
5721 if (QT & Decl::OBJC_TQ_Inout)
5722 S += 'N';
5723 if (QT & Decl::OBJC_TQ_Out)
5724 S += 'o';
5725 if (QT & Decl::OBJC_TQ_Bycopy)
5726 S += 'O';
5727 if (QT & Decl::OBJC_TQ_Byref)
5728 S += 'R';
5729 if (QT & Decl::OBJC_TQ_Oneway)
5730 S += 'V';
5731}
5732
Douglas Gregor3ea72692011-08-12 05:46:01 +00005733TypedefDecl *ASTContext::getObjCIdDecl() const {
5734 if (!ObjCIdDecl) {
5735 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5736 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005737 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005738 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005739 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005740}
5741
Douglas Gregor52e02802011-08-12 06:17:30 +00005742TypedefDecl *ASTContext::getObjCSelDecl() const {
5743 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005744 QualType T = getPointerType(ObjCBuiltinSelTy);
5745 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005746 }
5747 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005748}
5749
Douglas Gregor0a586182011-08-12 05:59:41 +00005750TypedefDecl *ASTContext::getObjCClassDecl() const {
5751 if (!ObjCClassDecl) {
5752 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5753 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005754 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005755 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005756 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005757}
5758
Douglas Gregord53ae832012-01-17 18:09:05 +00005759ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5760 if (!ObjCProtocolClassDecl) {
5761 ObjCProtocolClassDecl
5762 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5763 SourceLocation(),
5764 &Idents.get("Protocol"),
5765 /*PrevDecl=*/0,
5766 SourceLocation(), true);
5767 }
5768
5769 return ObjCProtocolClassDecl;
5770}
5771
Meador Inge5d3fb222012-06-16 03:34:49 +00005772//===----------------------------------------------------------------------===//
5773// __builtin_va_list Construction Functions
5774//===----------------------------------------------------------------------===//
5775
5776static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5777 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005778 QualType T = Context->getPointerType(Context->CharTy);
5779 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005780}
5781
5782static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5783 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005784 QualType T = Context->getPointerType(Context->VoidTy);
5785 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005786}
5787
Tim Northover9bb857a2013-01-31 12:13:10 +00005788static TypedefDecl *
5789CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005790 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005791 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005792 if (Context->getLangOpts().CPlusPlus) {
5793 // namespace std { struct __va_list {
5794 NamespaceDecl *NS;
5795 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5796 Context->getTranslationUnitDecl(),
5797 /*Inline*/false, SourceLocation(),
5798 SourceLocation(), &Context->Idents.get("std"),
5799 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005800 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005801 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005802 }
5803
5804 VaListTagDecl->startDefinition();
5805
5806 const size_t NumFields = 5;
5807 QualType FieldTypes[NumFields];
5808 const char *FieldNames[NumFields];
5809
5810 // void *__stack;
5811 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5812 FieldNames[0] = "__stack";
5813
5814 // void *__gr_top;
5815 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5816 FieldNames[1] = "__gr_top";
5817
5818 // void *__vr_top;
5819 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5820 FieldNames[2] = "__vr_top";
5821
5822 // int __gr_offs;
5823 FieldTypes[3] = Context->IntTy;
5824 FieldNames[3] = "__gr_offs";
5825
5826 // int __vr_offs;
5827 FieldTypes[4] = Context->IntTy;
5828 FieldNames[4] = "__vr_offs";
5829
5830 // Create fields
5831 for (unsigned i = 0; i < NumFields; ++i) {
5832 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5833 VaListTagDecl,
5834 SourceLocation(),
5835 SourceLocation(),
5836 &Context->Idents.get(FieldNames[i]),
5837 FieldTypes[i], /*TInfo=*/0,
5838 /*BitWidth=*/0,
5839 /*Mutable=*/false,
5840 ICIS_NoInit);
5841 Field->setAccess(AS_public);
5842 VaListTagDecl->addDecl(Field);
5843 }
5844 VaListTagDecl->completeDefinition();
5845 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5846 Context->VaListTagTy = VaListTagType;
5847
5848 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005849 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005850}
5851
Meador Inge5d3fb222012-06-16 03:34:49 +00005852static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5853 // typedef struct __va_list_tag {
5854 RecordDecl *VaListTagDecl;
5855
Alp Toker2dea15b2013-12-17 01:22:38 +00005856 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005857 VaListTagDecl->startDefinition();
5858
5859 const size_t NumFields = 5;
5860 QualType FieldTypes[NumFields];
5861 const char *FieldNames[NumFields];
5862
5863 // unsigned char gpr;
5864 FieldTypes[0] = Context->UnsignedCharTy;
5865 FieldNames[0] = "gpr";
5866
5867 // unsigned char fpr;
5868 FieldTypes[1] = Context->UnsignedCharTy;
5869 FieldNames[1] = "fpr";
5870
5871 // unsigned short reserved;
5872 FieldTypes[2] = Context->UnsignedShortTy;
5873 FieldNames[2] = "reserved";
5874
5875 // void* overflow_arg_area;
5876 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5877 FieldNames[3] = "overflow_arg_area";
5878
5879 // void* reg_save_area;
5880 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5881 FieldNames[4] = "reg_save_area";
5882
5883 // Create fields
5884 for (unsigned i = 0; i < NumFields; ++i) {
5885 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5886 SourceLocation(),
5887 SourceLocation(),
5888 &Context->Idents.get(FieldNames[i]),
5889 FieldTypes[i], /*TInfo=*/0,
5890 /*BitWidth=*/0,
5891 /*Mutable=*/false,
5892 ICIS_NoInit);
5893 Field->setAccess(AS_public);
5894 VaListTagDecl->addDecl(Field);
5895 }
5896 VaListTagDecl->completeDefinition();
5897 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005898 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005899
5900 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005901 TypedefDecl *VaListTagTypedefDecl =
5902 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5903
Meador Inge5d3fb222012-06-16 03:34:49 +00005904 QualType VaListTagTypedefType =
5905 Context->getTypedefType(VaListTagTypedefDecl);
5906
5907 // typedef __va_list_tag __builtin_va_list[1];
5908 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5909 QualType VaListTagArrayType
5910 = Context->getConstantArrayType(VaListTagTypedefType,
5911 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005912 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005913}
5914
5915static TypedefDecl *
5916CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5917 // typedef struct __va_list_tag {
5918 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005919 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005920 VaListTagDecl->startDefinition();
5921
5922 const size_t NumFields = 4;
5923 QualType FieldTypes[NumFields];
5924 const char *FieldNames[NumFields];
5925
5926 // unsigned gp_offset;
5927 FieldTypes[0] = Context->UnsignedIntTy;
5928 FieldNames[0] = "gp_offset";
5929
5930 // unsigned fp_offset;
5931 FieldTypes[1] = Context->UnsignedIntTy;
5932 FieldNames[1] = "fp_offset";
5933
5934 // void* overflow_arg_area;
5935 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5936 FieldNames[2] = "overflow_arg_area";
5937
5938 // void* reg_save_area;
5939 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5940 FieldNames[3] = "reg_save_area";
5941
5942 // Create fields
5943 for (unsigned i = 0; i < NumFields; ++i) {
5944 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5945 VaListTagDecl,
5946 SourceLocation(),
5947 SourceLocation(),
5948 &Context->Idents.get(FieldNames[i]),
5949 FieldTypes[i], /*TInfo=*/0,
5950 /*BitWidth=*/0,
5951 /*Mutable=*/false,
5952 ICIS_NoInit);
5953 Field->setAccess(AS_public);
5954 VaListTagDecl->addDecl(Field);
5955 }
5956 VaListTagDecl->completeDefinition();
5957 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005958 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005959
5960 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005961 TypedefDecl *VaListTagTypedefDecl =
5962 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5963
Meador Inge5d3fb222012-06-16 03:34:49 +00005964 QualType VaListTagTypedefType =
5965 Context->getTypedefType(VaListTagTypedefDecl);
5966
5967 // typedef __va_list_tag __builtin_va_list[1];
5968 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5969 QualType VaListTagArrayType
5970 = Context->getConstantArrayType(VaListTagTypedefType,
5971 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005972 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005973}
5974
5975static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5976 // typedef int __builtin_va_list[4];
5977 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5978 QualType IntArrayType
5979 = Context->getConstantArrayType(Context->IntTy,
5980 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005981 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005982}
5983
Logan Chien57086ce2012-10-10 06:56:20 +00005984static TypedefDecl *
5985CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005986 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005987 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005988 if (Context->getLangOpts().CPlusPlus) {
5989 // namespace std { struct __va_list {
5990 NamespaceDecl *NS;
5991 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5992 Context->getTranslationUnitDecl(),
5993 /*Inline*/false, SourceLocation(),
5994 SourceLocation(), &Context->Idents.get("std"),
5995 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005996 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00005997 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00005998 }
5999
6000 VaListDecl->startDefinition();
6001
6002 // void * __ap;
6003 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6004 VaListDecl,
6005 SourceLocation(),
6006 SourceLocation(),
6007 &Context->Idents.get("__ap"),
6008 Context->getPointerType(Context->VoidTy),
6009 /*TInfo=*/0,
6010 /*BitWidth=*/0,
6011 /*Mutable=*/false,
6012 ICIS_NoInit);
6013 Field->setAccess(AS_public);
6014 VaListDecl->addDecl(Field);
6015
6016 // };
6017 VaListDecl->completeDefinition();
6018
6019 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006020 QualType T = Context->getRecordType(VaListDecl);
6021 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006022}
6023
Ulrich Weigand47445072013-05-06 16:26:41 +00006024static TypedefDecl *
6025CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6026 // typedef struct __va_list_tag {
6027 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006028 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006029 VaListTagDecl->startDefinition();
6030
6031 const size_t NumFields = 4;
6032 QualType FieldTypes[NumFields];
6033 const char *FieldNames[NumFields];
6034
6035 // long __gpr;
6036 FieldTypes[0] = Context->LongTy;
6037 FieldNames[0] = "__gpr";
6038
6039 // long __fpr;
6040 FieldTypes[1] = Context->LongTy;
6041 FieldNames[1] = "__fpr";
6042
6043 // void *__overflow_arg_area;
6044 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6045 FieldNames[2] = "__overflow_arg_area";
6046
6047 // void *__reg_save_area;
6048 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6049 FieldNames[3] = "__reg_save_area";
6050
6051 // Create fields
6052 for (unsigned i = 0; i < NumFields; ++i) {
6053 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6054 VaListTagDecl,
6055 SourceLocation(),
6056 SourceLocation(),
6057 &Context->Idents.get(FieldNames[i]),
6058 FieldTypes[i], /*TInfo=*/0,
6059 /*BitWidth=*/0,
6060 /*Mutable=*/false,
6061 ICIS_NoInit);
6062 Field->setAccess(AS_public);
6063 VaListTagDecl->addDecl(Field);
6064 }
6065 VaListTagDecl->completeDefinition();
6066 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6067 Context->VaListTagTy = VaListTagType;
6068
6069 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006070 TypedefDecl *VaListTagTypedefDecl =
6071 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006072 QualType VaListTagTypedefType =
6073 Context->getTypedefType(VaListTagTypedefDecl);
6074
6075 // typedef __va_list_tag __builtin_va_list[1];
6076 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6077 QualType VaListTagArrayType
6078 = Context->getConstantArrayType(VaListTagTypedefType,
6079 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006080
Alp Toker56b5cc92013-12-15 10:36:26 +00006081 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006082}
6083
Meador Inge5d3fb222012-06-16 03:34:49 +00006084static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6085 TargetInfo::BuiltinVaListKind Kind) {
6086 switch (Kind) {
6087 case TargetInfo::CharPtrBuiltinVaList:
6088 return CreateCharPtrBuiltinVaListDecl(Context);
6089 case TargetInfo::VoidPtrBuiltinVaList:
6090 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006091 case TargetInfo::AArch64ABIBuiltinVaList:
6092 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006093 case TargetInfo::PowerABIBuiltinVaList:
6094 return CreatePowerABIBuiltinVaListDecl(Context);
6095 case TargetInfo::X86_64ABIBuiltinVaList:
6096 return CreateX86_64ABIBuiltinVaListDecl(Context);
6097 case TargetInfo::PNaClABIBuiltinVaList:
6098 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006099 case TargetInfo::AAPCSABIBuiltinVaList:
6100 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006101 case TargetInfo::SystemZBuiltinVaList:
6102 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006103 }
6104
6105 llvm_unreachable("Unhandled __builtin_va_list type kind");
6106}
6107
6108TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006109 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006110 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006111 assert(BuiltinVaListDecl->isImplicit());
6112 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006113
6114 return BuiltinVaListDecl;
6115}
6116
Meador Ingecfb60902012-07-01 15:57:25 +00006117QualType ASTContext::getVaListTagType() const {
6118 // Force the creation of VaListTagTy by building the __builtin_va_list
6119 // declaration.
6120 if (VaListTagTy.isNull())
6121 (void) getBuiltinVaListDecl();
6122
6123 return VaListTagTy;
6124}
6125
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006126void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006127 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006128 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006129
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006130 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006131}
6132
John McCalld28ae272009-12-02 08:04:21 +00006133/// \brief Retrieve the template name that corresponds to a non-empty
6134/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006135TemplateName
6136ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6137 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006138 unsigned size = End - Begin;
6139 assert(size > 1 && "set is not overloaded!");
6140
6141 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6142 size * sizeof(FunctionTemplateDecl*));
6143 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6144
6145 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006146 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006147 NamedDecl *D = *I;
6148 assert(isa<FunctionTemplateDecl>(D) ||
6149 (isa<UsingShadowDecl>(D) &&
6150 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6151 *Storage++ = D;
6152 }
6153
6154 return TemplateName(OT);
6155}
6156
Douglas Gregordc572a32009-03-30 22:58:21 +00006157/// \brief Retrieve the template name that represents a qualified
6158/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006159TemplateName
6160ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6161 bool TemplateKeyword,
6162 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006163 assert(NNS && "Missing nested-name-specifier in qualified template name");
6164
Douglas Gregorc42075a2010-02-04 18:10:26 +00006165 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006166 llvm::FoldingSetNodeID ID;
6167 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6168
6169 void *InsertPos = 0;
6170 QualifiedTemplateName *QTN =
6171 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6172 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006173 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6174 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006175 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6176 }
6177
6178 return TemplateName(QTN);
6179}
6180
6181/// \brief Retrieve the template name that represents a dependent
6182/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006183TemplateName
6184ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6185 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006186 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006187 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006188
6189 llvm::FoldingSetNodeID ID;
6190 DependentTemplateName::Profile(ID, NNS, Name);
6191
6192 void *InsertPos = 0;
6193 DependentTemplateName *QTN =
6194 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6195
6196 if (QTN)
6197 return TemplateName(QTN);
6198
6199 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6200 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006201 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6202 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006203 } else {
6204 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006205 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6206 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006207 DependentTemplateName *CheckQTN =
6208 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6209 assert(!CheckQTN && "Dependent type name canonicalization broken");
6210 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006211 }
6212
6213 DependentTemplateNames.InsertNode(QTN, InsertPos);
6214 return TemplateName(QTN);
6215}
6216
Douglas Gregor71395fa2009-11-04 00:56:37 +00006217/// \brief Retrieve the template name that represents a dependent
6218/// template name such as \c MetaFun::template operator+.
6219TemplateName
6220ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006221 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006222 assert((!NNS || NNS->isDependent()) &&
6223 "Nested name specifier must be dependent");
6224
6225 llvm::FoldingSetNodeID ID;
6226 DependentTemplateName::Profile(ID, NNS, Operator);
6227
6228 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006229 DependentTemplateName *QTN
6230 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006231
6232 if (QTN)
6233 return TemplateName(QTN);
6234
6235 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6236 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006237 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6238 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006239 } else {
6240 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006241 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6242 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006243
6244 DependentTemplateName *CheckQTN
6245 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6246 assert(!CheckQTN && "Dependent template name canonicalization broken");
6247 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006248 }
6249
6250 DependentTemplateNames.InsertNode(QTN, InsertPos);
6251 return TemplateName(QTN);
6252}
6253
Douglas Gregor5590be02011-01-15 06:45:20 +00006254TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006255ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6256 TemplateName replacement) const {
6257 llvm::FoldingSetNodeID ID;
6258 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6259
6260 void *insertPos = 0;
6261 SubstTemplateTemplateParmStorage *subst
6262 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6263
6264 if (!subst) {
6265 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6266 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6267 }
6268
6269 return TemplateName(subst);
6270}
6271
6272TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006273ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6274 const TemplateArgument &ArgPack) const {
6275 ASTContext &Self = const_cast<ASTContext &>(*this);
6276 llvm::FoldingSetNodeID ID;
6277 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6278
6279 void *InsertPos = 0;
6280 SubstTemplateTemplateParmPackStorage *Subst
6281 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6282
6283 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006284 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006285 ArgPack.pack_size(),
6286 ArgPack.pack_begin());
6287 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6288 }
6289
6290 return TemplateName(Subst);
6291}
6292
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006293/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006294/// TargetInfo, produce the corresponding type. The unsigned @p Type
6295/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006296CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006297 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006298 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006299 case TargetInfo::SignedChar: return SignedCharTy;
6300 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006301 case TargetInfo::SignedShort: return ShortTy;
6302 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6303 case TargetInfo::SignedInt: return IntTy;
6304 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6305 case TargetInfo::SignedLong: return LongTy;
6306 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6307 case TargetInfo::SignedLongLong: return LongLongTy;
6308 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6309 }
6310
David Blaikie83d382b2011-09-23 05:06:16 +00006311 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006312}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006313
6314//===----------------------------------------------------------------------===//
6315// Type Predicates.
6316//===----------------------------------------------------------------------===//
6317
Fariborz Jahanian96207692009-02-18 21:49:28 +00006318/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6319/// garbage collection attribute.
6320///
John McCall553d45a2011-01-12 00:34:59 +00006321Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006322 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006323 return Qualifiers::GCNone;
6324
David Blaikiebbafb8a2012-03-11 07:00:24 +00006325 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006326 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6327
6328 // Default behaviour under objective-C's gc is for ObjC pointers
6329 // (or pointers to them) be treated as though they were declared
6330 // as __strong.
6331 if (GCAttrs == Qualifiers::GCNone) {
6332 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6333 return Qualifiers::Strong;
6334 else if (Ty->isPointerType())
6335 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6336 } else {
6337 // It's not valid to set GC attributes on anything that isn't a
6338 // pointer.
6339#ifndef NDEBUG
6340 QualType CT = Ty->getCanonicalTypeInternal();
6341 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6342 CT = AT->getElementType();
6343 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6344#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006345 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006346 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006347}
6348
Chris Lattner49af6a42008-04-07 06:51:04 +00006349//===----------------------------------------------------------------------===//
6350// Type Compatibility Testing
6351//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006352
Mike Stump11289f42009-09-09 15:08:12 +00006353/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006354/// compatible.
6355static bool areCompatVectorTypes(const VectorType *LHS,
6356 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006357 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006358 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006359 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006360}
6361
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006362bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6363 QualType SecondVec) {
6364 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6365 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6366
6367 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6368 return true;
6369
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006370 // Treat Neon vector types and most AltiVec vector types as if they are the
6371 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006372 const VectorType *First = FirstVec->getAs<VectorType>();
6373 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006374 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006375 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006376 First->getVectorKind() != VectorType::AltiVecPixel &&
6377 First->getVectorKind() != VectorType::AltiVecBool &&
6378 Second->getVectorKind() != VectorType::AltiVecPixel &&
6379 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006380 return true;
6381
6382 return false;
6383}
6384
Steve Naroff8e6aee52009-07-23 01:01:38 +00006385//===----------------------------------------------------------------------===//
6386// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6387//===----------------------------------------------------------------------===//
6388
6389/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6390/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006391bool
6392ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6393 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006394 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006395 return true;
6396 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6397 E = rProto->protocol_end(); PI != E; ++PI)
6398 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6399 return true;
6400 return false;
6401}
6402
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006403/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6404/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006405bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6406 QualType rhs) {
6407 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6408 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6409 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6410
6411 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6412 E = lhsQID->qual_end(); I != E; ++I) {
6413 bool match = false;
6414 ObjCProtocolDecl *lhsProto = *I;
6415 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6416 E = rhsOPT->qual_end(); J != E; ++J) {
6417 ObjCProtocolDecl *rhsProto = *J;
6418 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6419 match = true;
6420 break;
6421 }
6422 }
6423 if (!match)
6424 return false;
6425 }
6426 return true;
6427}
6428
Steve Naroff8e6aee52009-07-23 01:01:38 +00006429/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6430/// ObjCQualifiedIDType.
6431bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6432 bool compare) {
6433 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006434 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006435 lhs->isObjCIdType() || lhs->isObjCClassType())
6436 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006437 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006438 rhs->isObjCIdType() || rhs->isObjCClassType())
6439 return true;
6440
6441 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006442 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006443
Steve Naroff8e6aee52009-07-23 01:01:38 +00006444 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006445
Steve Naroff8e6aee52009-07-23 01:01:38 +00006446 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006447 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006448 // make sure we check the class hierarchy.
6449 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6450 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6451 E = lhsQID->qual_end(); I != E; ++I) {
6452 // when comparing an id<P> on lhs with a static type on rhs,
6453 // see if static class implements all of id's protocols, directly or
6454 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006455 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006456 return false;
6457 }
6458 }
6459 // If there are no qualifiers and no interface, we have an 'id'.
6460 return true;
6461 }
Mike Stump11289f42009-09-09 15:08:12 +00006462 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006463 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6464 E = lhsQID->qual_end(); I != E; ++I) {
6465 ObjCProtocolDecl *lhsProto = *I;
6466 bool match = false;
6467
6468 // when comparing an id<P> on lhs with a static type on rhs,
6469 // see if static class implements all of id's protocols, directly or
6470 // through its super class and categories.
6471 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6472 E = rhsOPT->qual_end(); J != E; ++J) {
6473 ObjCProtocolDecl *rhsProto = *J;
6474 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6475 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6476 match = true;
6477 break;
6478 }
6479 }
Mike Stump11289f42009-09-09 15:08:12 +00006480 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006481 // make sure we check the class hierarchy.
6482 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6483 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6484 E = lhsQID->qual_end(); I != E; ++I) {
6485 // when comparing an id<P> on lhs with a static type on rhs,
6486 // see if static class implements all of id's protocols, directly or
6487 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006488 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006489 match = true;
6490 break;
6491 }
6492 }
6493 }
6494 if (!match)
6495 return false;
6496 }
Mike Stump11289f42009-09-09 15:08:12 +00006497
Steve Naroff8e6aee52009-07-23 01:01:38 +00006498 return true;
6499 }
Mike Stump11289f42009-09-09 15:08:12 +00006500
Steve Naroff8e6aee52009-07-23 01:01:38 +00006501 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6502 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6503
Mike Stump11289f42009-09-09 15:08:12 +00006504 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006505 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006506 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006507 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6508 E = lhsOPT->qual_end(); I != E; ++I) {
6509 ObjCProtocolDecl *lhsProto = *I;
6510 bool match = false;
6511
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006512 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006513 // see if static class implements all of id's protocols, directly or
6514 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006515 // First, lhs protocols in the qualifier list must be found, direct
6516 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006517 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6518 E = rhsQID->qual_end(); J != E; ++J) {
6519 ObjCProtocolDecl *rhsProto = *J;
6520 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6521 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6522 match = true;
6523 break;
6524 }
6525 }
6526 if (!match)
6527 return false;
6528 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006529
6530 // Static class's protocols, or its super class or category protocols
6531 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6532 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6533 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6534 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6535 // This is rather dubious but matches gcc's behavior. If lhs has
6536 // no type qualifier and its class has no static protocol(s)
6537 // assume that it is mismatch.
6538 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6539 return false;
6540 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6541 LHSInheritedProtocols.begin(),
6542 E = LHSInheritedProtocols.end(); I != E; ++I) {
6543 bool match = false;
6544 ObjCProtocolDecl *lhsProto = (*I);
6545 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6546 E = rhsQID->qual_end(); J != E; ++J) {
6547 ObjCProtocolDecl *rhsProto = *J;
6548 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6549 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6550 match = true;
6551 break;
6552 }
6553 }
6554 if (!match)
6555 return false;
6556 }
6557 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006558 return true;
6559 }
6560 return false;
6561}
6562
Eli Friedman47f77112008-08-22 00:56:42 +00006563/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006564/// compatible for assignment from RHS to LHS. This handles validation of any
6565/// protocol qualifiers on the LHS or RHS.
6566///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006567bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6568 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006569 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6570 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6571
Steve Naroff1329fa02009-07-15 18:40:39 +00006572 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006573 if (LHS->isObjCUnqualifiedIdOrClass() ||
6574 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006575 return true;
6576
John McCall8b07ec22010-05-15 11:32:37 +00006577 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006578 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6579 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006580 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006581
6582 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6583 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6584 QualType(RHSOPT,0));
6585
John McCall8b07ec22010-05-15 11:32:37 +00006586 // If we have 2 user-defined types, fall into that path.
6587 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006588 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006589
Steve Naroff8e6aee52009-07-23 01:01:38 +00006590 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006591}
6592
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006593/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006594/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006595/// arguments in block literals. When passed as arguments, passing 'A*' where
6596/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6597/// not OK. For the return type, the opposite is not OK.
6598bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6599 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006600 const ObjCObjectPointerType *RHSOPT,
6601 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006602 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006603 return true;
6604
6605 if (LHSOPT->isObjCBuiltinType()) {
6606 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6607 }
6608
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006609 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006610 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6611 QualType(RHSOPT,0),
6612 false);
6613
6614 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6615 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6616 if (LHS && RHS) { // We have 2 user-defined types.
6617 if (LHS != RHS) {
6618 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006619 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006620 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006621 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006622 }
6623 else
6624 return true;
6625 }
6626 return false;
6627}
6628
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006629/// getIntersectionOfProtocols - This routine finds the intersection of set
6630/// of protocols inherited from two distinct objective-c pointer objects.
6631/// It is used to build composite qualifier list of the composite type of
6632/// the conditional expression involving two objective-c pointer objects.
6633static
6634void getIntersectionOfProtocols(ASTContext &Context,
6635 const ObjCObjectPointerType *LHSOPT,
6636 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006637 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006638
John McCall8b07ec22010-05-15 11:32:37 +00006639 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6640 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6641 assert(LHS->getInterface() && "LHS must have an interface base");
6642 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006643
6644 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6645 unsigned LHSNumProtocols = LHS->getNumProtocols();
6646 if (LHSNumProtocols > 0)
6647 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6648 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006649 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006650 Context.CollectInheritedProtocols(LHS->getInterface(),
6651 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006652 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6653 LHSInheritedProtocols.end());
6654 }
6655
6656 unsigned RHSNumProtocols = RHS->getNumProtocols();
6657 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006658 ObjCProtocolDecl **RHSProtocols =
6659 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006660 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6661 if (InheritedProtocolSet.count(RHSProtocols[i]))
6662 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006663 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006664 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006665 Context.CollectInheritedProtocols(RHS->getInterface(),
6666 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006667 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6668 RHSInheritedProtocols.begin(),
6669 E = RHSInheritedProtocols.end(); I != E; ++I)
6670 if (InheritedProtocolSet.count((*I)))
6671 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006672 }
6673}
6674
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006675/// areCommonBaseCompatible - Returns common base class of the two classes if
6676/// one found. Note that this is O'2 algorithm. But it will be called as the
6677/// last type comparison in a ?-exp of ObjC pointer types before a
6678/// warning is issued. So, its invokation is extremely rare.
6679QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006680 const ObjCObjectPointerType *Lptr,
6681 const ObjCObjectPointerType *Rptr) {
6682 const ObjCObjectType *LHS = Lptr->getObjectType();
6683 const ObjCObjectType *RHS = Rptr->getObjectType();
6684 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6685 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006686 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006687 return QualType();
6688
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006689 do {
John McCall8b07ec22010-05-15 11:32:37 +00006690 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006691 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006692 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006693 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6694
6695 QualType Result = QualType(LHS, 0);
6696 if (!Protocols.empty())
6697 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6698 Result = getObjCObjectPointerType(Result);
6699 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006700 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006701 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006702
6703 return QualType();
6704}
6705
John McCall8b07ec22010-05-15 11:32:37 +00006706bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6707 const ObjCObjectType *RHS) {
6708 assert(LHS->getInterface() && "LHS is not an interface type");
6709 assert(RHS->getInterface() && "RHS is not an interface type");
6710
Chris Lattner49af6a42008-04-07 06:51:04 +00006711 // Verify that the base decls are compatible: the RHS must be a subclass of
6712 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006713 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006714 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006715
Chris Lattner49af6a42008-04-07 06:51:04 +00006716 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6717 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006718 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006719 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006720
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006721 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6722 // more detailed analysis is required.
6723 if (RHS->getNumProtocols() == 0) {
6724 // OK, if LHS is a superclass of RHS *and*
6725 // this superclass is assignment compatible with LHS.
6726 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006727 bool IsSuperClass =
6728 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6729 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006730 // OK if conversion of LHS to SuperClass results in narrowing of types
6731 // ; i.e., SuperClass may implement at least one of the protocols
6732 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6733 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6734 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006735 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006736 // If super class has no protocols, it is not a match.
6737 if (SuperClassInheritedProtocols.empty())
6738 return false;
6739
6740 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6741 LHSPE = LHS->qual_end();
6742 LHSPI != LHSPE; LHSPI++) {
6743 bool SuperImplementsProtocol = false;
6744 ObjCProtocolDecl *LHSProto = (*LHSPI);
6745
6746 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6747 SuperClassInheritedProtocols.begin(),
6748 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6749 ObjCProtocolDecl *SuperClassProto = (*I);
6750 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6751 SuperImplementsProtocol = true;
6752 break;
6753 }
6754 }
6755 if (!SuperImplementsProtocol)
6756 return false;
6757 }
6758 return true;
6759 }
6760 return false;
6761 }
Mike Stump11289f42009-09-09 15:08:12 +00006762
John McCall8b07ec22010-05-15 11:32:37 +00006763 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6764 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006765 LHSPI != LHSPE; LHSPI++) {
6766 bool RHSImplementsProtocol = false;
6767
6768 // If the RHS doesn't implement the protocol on the left, the types
6769 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006770 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6771 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006772 RHSPI != RHSPE; RHSPI++) {
6773 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006774 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006775 break;
6776 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006777 }
6778 // FIXME: For better diagnostics, consider passing back the protocol name.
6779 if (!RHSImplementsProtocol)
6780 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006781 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006782 // The RHS implements all protocols listed on the LHS.
6783 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006784}
6785
Steve Naroffb7605152009-02-12 17:52:19 +00006786bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6787 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006788 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6789 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006790
Steve Naroff7cae42b2009-07-10 23:34:53 +00006791 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006792 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006793
6794 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6795 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006796}
6797
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006798bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6799 return canAssignObjCInterfaces(
6800 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6801 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6802}
6803
Mike Stump11289f42009-09-09 15:08:12 +00006804/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006805/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006806/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006807/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006808bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6809 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006810 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006811 return hasSameType(LHS, RHS);
6812
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006813 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006814}
6815
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006816bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006817 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006818}
6819
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006820bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6821 return !mergeTypes(LHS, RHS, true).isNull();
6822}
6823
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006824/// mergeTransparentUnionType - if T is a transparent union type and a member
6825/// of T is compatible with SubType, return the merged type, else return
6826/// QualType()
6827QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6828 bool OfBlockPointer,
6829 bool Unqualified) {
6830 if (const RecordType *UT = T->getAsUnionType()) {
6831 RecordDecl *UD = UT->getDecl();
6832 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006833 for (const auto *I : UD->fields()) {
6834 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006835 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6836 if (!MT.isNull())
6837 return MT;
6838 }
6839 }
6840 }
6841
6842 return QualType();
6843}
6844
Alp Toker9cacbab2014-01-20 20:26:09 +00006845/// mergeFunctionParameterTypes - merge two types which appear as function
6846/// parameter types
6847QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6848 bool OfBlockPointer,
6849 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006850 // GNU extension: two types are compatible if they appear as a function
6851 // argument, one of the types is a transparent union type and the other
6852 // type is compatible with a union member
6853 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6854 Unqualified);
6855 if (!lmerge.isNull())
6856 return lmerge;
6857
6858 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6859 Unqualified);
6860 if (!rmerge.isNull())
6861 return rmerge;
6862
6863 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6864}
6865
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006866QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006867 bool OfBlockPointer,
6868 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006869 const FunctionType *lbase = lhs->getAs<FunctionType>();
6870 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006871 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6872 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006873 bool allLTypes = true;
6874 bool allRTypes = true;
6875
6876 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006877 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006878 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006879 QualType RHS = rbase->getReturnType();
6880 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006881 bool UnqualifiedResult = Unqualified;
6882 if (!UnqualifiedResult)
6883 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006884 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006885 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006886 else
Alp Toker314cc812014-01-25 16:55:45 +00006887 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006888 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006889 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006890
6891 if (Unqualified)
6892 retType = retType.getUnqualifiedType();
6893
Alp Toker314cc812014-01-25 16:55:45 +00006894 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6895 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006896 if (Unqualified) {
6897 LRetType = LRetType.getUnqualifiedType();
6898 RRetType = RRetType.getUnqualifiedType();
6899 }
6900
6901 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006902 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006903 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006904 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006905
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006906 // FIXME: double check this
6907 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6908 // rbase->getRegParmAttr() != 0 &&
6909 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006910 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6911 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006912
Douglas Gregor8c940862010-01-18 17:14:39 +00006913 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006914 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006915 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006916
John McCall8c6b56f2010-12-15 01:06:38 +00006917 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006918 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6919 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006920 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6921 return QualType();
6922
John McCall31168b02011-06-15 23:02:42 +00006923 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6924 return QualType();
6925
John McCall8c6b56f2010-12-15 01:06:38 +00006926 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6927 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006928
Rafael Espindola8778c282012-11-29 16:09:03 +00006929 if (lbaseInfo.getNoReturn() != NoReturn)
6930 allLTypes = false;
6931 if (rbaseInfo.getNoReturn() != NoReturn)
6932 allRTypes = false;
6933
John McCall31168b02011-06-15 23:02:42 +00006934 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006935
Eli Friedman47f77112008-08-22 00:56:42 +00006936 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006937 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6938 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006939 // Compatible functions must have the same number of parameters
6940 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006941 return QualType();
6942
6943 // Variadic and non-variadic functions aren't compatible
6944 if (lproto->isVariadic() != rproto->isVariadic())
6945 return QualType();
6946
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006947 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6948 return QualType();
6949
Fariborz Jahanian97676972011-09-28 21:52:05 +00006950 if (LangOpts.ObjCAutoRefCount &&
6951 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6952 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006953
6954 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006955 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006956 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6957 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6958 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6959 QualType paramType = mergeFunctionParameterTypes(
6960 lParamType, rParamType, OfBlockPointer, Unqualified);
6961 if (paramType.isNull())
6962 return QualType();
6963
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006964 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006965 paramType = paramType.getUnqualifiedType();
6966
6967 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006968 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006969 lParamType = lParamType.getUnqualifiedType();
6970 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006971 }
Alp Toker601b22c2014-01-21 23:35:24 +00006972
6973 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006974 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006975 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006976 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006977 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006978
Eli Friedman47f77112008-08-22 00:56:42 +00006979 if (allLTypes) return lhs;
6980 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006981
6982 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6983 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006984 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006985 }
6986
6987 if (lproto) allRTypes = false;
6988 if (rproto) allLTypes = false;
6989
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006990 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006991 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006992 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006993 if (proto->isVariadic()) return QualType();
6994 // Check that the types are compatible with the types that
6995 // would result from default argument promotions (C99 6.7.5.3p15).
6996 // The only types actually affected are promotable integer
6997 // types and floats, which would be passed as a different
6998 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00006999 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7000 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007001
Eli Friedman448ce402012-08-30 00:44:15 +00007002 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007003 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007004 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7005 paramTy = Enum->getDecl()->getIntegerType();
7006 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007007 return QualType();
7008 }
Alp Toker601b22c2014-01-21 23:35:24 +00007009
7010 if (paramTy->isPromotableIntegerType() ||
7011 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007012 return QualType();
7013 }
7014
7015 if (allLTypes) return lhs;
7016 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007017
7018 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7019 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007020 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007021 }
7022
7023 if (allLTypes) return lhs;
7024 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007025 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007026}
7027
John McCall433c2e62013-03-21 00:10:07 +00007028/// Given that we have an enum type and a non-enum type, try to merge them.
7029static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7030 QualType other, bool isBlockReturnType) {
7031 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7032 // a signed integer type, or an unsigned integer type.
7033 // Compatibility is based on the underlying type, not the promotion
7034 // type.
7035 QualType underlyingType = ET->getDecl()->getIntegerType();
7036 if (underlyingType.isNull()) return QualType();
7037 if (Context.hasSameType(underlyingType, other))
7038 return other;
7039
7040 // In block return types, we're more permissive and accept any
7041 // integral type of the same size.
7042 if (isBlockReturnType && other->isIntegerType() &&
7043 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7044 return other;
7045
7046 return QualType();
7047}
7048
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007049QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007050 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007051 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007052 // C++ [expr]: If an expression initially has the type "reference to T", the
7053 // type is adjusted to "T" prior to any further analysis, the expression
7054 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007055 // expression is an lvalue unless the reference is an rvalue reference and
7056 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007057 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7058 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007059
7060 if (Unqualified) {
7061 LHS = LHS.getUnqualifiedType();
7062 RHS = RHS.getUnqualifiedType();
7063 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007064
Eli Friedman47f77112008-08-22 00:56:42 +00007065 QualType LHSCan = getCanonicalType(LHS),
7066 RHSCan = getCanonicalType(RHS);
7067
7068 // If two types are identical, they are compatible.
7069 if (LHSCan == RHSCan)
7070 return LHS;
7071
John McCall8ccfcb52009-09-24 19:53:00 +00007072 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007073 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7074 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007075 if (LQuals != RQuals) {
7076 // If any of these qualifiers are different, we have a type
7077 // mismatch.
7078 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007079 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7080 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007081 return QualType();
7082
7083 // Exactly one GC qualifier difference is allowed: __strong is
7084 // okay if the other type has no GC qualifier but is an Objective
7085 // C object pointer (i.e. implicitly strong by default). We fix
7086 // this by pretending that the unqualified type was actually
7087 // qualified __strong.
7088 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7089 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7090 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7091
7092 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7093 return QualType();
7094
7095 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7096 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7097 }
7098 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7099 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7100 }
Eli Friedman47f77112008-08-22 00:56:42 +00007101 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007102 }
7103
7104 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007105
Eli Friedmandcca6332009-06-01 01:22:52 +00007106 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7107 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007108
Chris Lattnerfd652912008-01-14 05:45:46 +00007109 // We want to consider the two function types to be the same for these
7110 // comparisons, just force one to the other.
7111 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7112 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007113
7114 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007115 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7116 LHSClass = Type::ConstantArray;
7117 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7118 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007119
John McCall8b07ec22010-05-15 11:32:37 +00007120 // ObjCInterfaces are just specialized ObjCObjects.
7121 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7122 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7123
Nate Begemance4d7fc2008-04-18 23:10:10 +00007124 // Canonicalize ExtVector -> Vector.
7125 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7126 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007127
Chris Lattner95554662008-04-07 05:43:21 +00007128 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007129 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007130 // Note that we only have special rules for turning block enum
7131 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007132 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007133 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007134 }
John McCall9dd450b2009-09-21 23:43:11 +00007135 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007136 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007137 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007138 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007139 if (OfBlockPointer && !BlockReturnType) {
7140 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7141 return LHS;
7142 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7143 return RHS;
7144 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007145
Eli Friedman47f77112008-08-22 00:56:42 +00007146 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007147 }
Eli Friedman47f77112008-08-22 00:56:42 +00007148
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007149 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007150 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007151#define TYPE(Class, Base)
7152#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007153#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007154#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7155#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7156#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007157 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007158
Richard Smith27d807c2013-04-30 13:56:41 +00007159 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007160 case Type::LValueReference:
7161 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007162 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007163 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007164
John McCall8b07ec22010-05-15 11:32:37 +00007165 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007166 case Type::IncompleteArray:
7167 case Type::VariableArray:
7168 case Type::FunctionProto:
7169 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007170 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007171
Chris Lattnerfd652912008-01-14 05:45:46 +00007172 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007173 {
7174 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007175 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7176 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007177 if (Unqualified) {
7178 LHSPointee = LHSPointee.getUnqualifiedType();
7179 RHSPointee = RHSPointee.getUnqualifiedType();
7180 }
7181 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7182 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007183 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007184 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007185 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007186 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007187 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007188 return getPointerType(ResultType);
7189 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007190 case Type::BlockPointer:
7191 {
7192 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007193 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7194 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007195 if (Unqualified) {
7196 LHSPointee = LHSPointee.getUnqualifiedType();
7197 RHSPointee = RHSPointee.getUnqualifiedType();
7198 }
7199 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7200 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007201 if (ResultType.isNull()) return QualType();
7202 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7203 return LHS;
7204 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7205 return RHS;
7206 return getBlockPointerType(ResultType);
7207 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007208 case Type::Atomic:
7209 {
7210 // Merge two pointer types, while trying to preserve typedef info
7211 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7212 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7213 if (Unqualified) {
7214 LHSValue = LHSValue.getUnqualifiedType();
7215 RHSValue = RHSValue.getUnqualifiedType();
7216 }
7217 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7218 Unqualified);
7219 if (ResultType.isNull()) return QualType();
7220 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7221 return LHS;
7222 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7223 return RHS;
7224 return getAtomicType(ResultType);
7225 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007226 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007227 {
7228 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7229 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7230 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7231 return QualType();
7232
7233 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7234 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007235 if (Unqualified) {
7236 LHSElem = LHSElem.getUnqualifiedType();
7237 RHSElem = RHSElem.getUnqualifiedType();
7238 }
7239
7240 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007241 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007242 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7243 return LHS;
7244 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7245 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007246 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7247 ArrayType::ArraySizeModifier(), 0);
7248 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7249 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007250 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7251 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007252 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7253 return LHS;
7254 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7255 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007256 if (LVAT) {
7257 // FIXME: This isn't correct! But tricky to implement because
7258 // the array's size has to be the size of LHS, but the type
7259 // has to be different.
7260 return LHS;
7261 }
7262 if (RVAT) {
7263 // FIXME: This isn't correct! But tricky to implement because
7264 // the array's size has to be the size of RHS, but the type
7265 // has to be different.
7266 return RHS;
7267 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007268 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7269 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007270 return getIncompleteArrayType(ResultType,
7271 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007272 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007273 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007274 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007275 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007276 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007277 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007278 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007279 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007280 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007281 case Type::Complex:
7282 // Distinct complex types are incompatible.
7283 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007284 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007285 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007286 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7287 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007288 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007289 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007290 case Type::ObjCObject: {
7291 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007292 // FIXME: This should be type compatibility, e.g. whether
7293 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007294 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7295 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7296 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007297 return LHS;
7298
Eli Friedman47f77112008-08-22 00:56:42 +00007299 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007300 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007301 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007302 if (OfBlockPointer) {
7303 if (canAssignObjCInterfacesInBlockPointer(
7304 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007305 RHS->getAs<ObjCObjectPointerType>(),
7306 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007307 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007308 return QualType();
7309 }
John McCall9dd450b2009-09-21 23:43:11 +00007310 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7311 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007312 return LHS;
7313
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007314 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007315 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007316 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007317
David Blaikie8a40f702012-01-17 06:56:22 +00007318 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007319}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007320
Fariborz Jahanian97676972011-09-28 21:52:05 +00007321bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7322 const FunctionProtoType *FromFunctionType,
7323 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007324 if (FromFunctionType->hasAnyConsumedParams() !=
7325 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007326 return false;
7327 FunctionProtoType::ExtProtoInfo FromEPI =
7328 FromFunctionType->getExtProtoInfo();
7329 FunctionProtoType::ExtProtoInfo ToEPI =
7330 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007331 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007332 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7333 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007334 return false;
7335 }
7336 return true;
7337}
7338
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007339/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7340/// 'RHS' attributes and returns the merged version; including for function
7341/// return types.
7342QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7343 QualType LHSCan = getCanonicalType(LHS),
7344 RHSCan = getCanonicalType(RHS);
7345 // If two types are identical, they are compatible.
7346 if (LHSCan == RHSCan)
7347 return LHS;
7348 if (RHSCan->isFunctionType()) {
7349 if (!LHSCan->isFunctionType())
7350 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007351 QualType OldReturnType =
7352 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007353 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007354 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007355 QualType ResReturnType =
7356 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7357 if (ResReturnType.isNull())
7358 return QualType();
7359 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7360 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7361 // In either case, use OldReturnType to build the new function type.
7362 const FunctionType *F = LHS->getAs<FunctionType>();
7363 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007364 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7365 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007366 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007367 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007368 return ResultType;
7369 }
7370 }
7371 return QualType();
7372 }
7373
7374 // If the qualifiers are different, the types can still be merged.
7375 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7376 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7377 if (LQuals != RQuals) {
7378 // If any of these qualifiers are different, we have a type mismatch.
7379 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7380 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7381 return QualType();
7382
7383 // Exactly one GC qualifier difference is allowed: __strong is
7384 // okay if the other type has no GC qualifier but is an Objective
7385 // C object pointer (i.e. implicitly strong by default). We fix
7386 // this by pretending that the unqualified type was actually
7387 // qualified __strong.
7388 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7389 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7390 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7391
7392 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7393 return QualType();
7394
7395 if (GC_L == Qualifiers::Strong)
7396 return LHS;
7397 if (GC_R == Qualifiers::Strong)
7398 return RHS;
7399 return QualType();
7400 }
7401
7402 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7403 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7404 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7405 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7406 if (ResQT == LHSBaseQT)
7407 return LHS;
7408 if (ResQT == RHSBaseQT)
7409 return RHS;
7410 }
7411 return QualType();
7412}
7413
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007414//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007415// Integer Predicates
7416//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007417
Jay Foad39c79802011-01-12 09:06:06 +00007418unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007419 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007420 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007421 if (T->isBooleanType())
7422 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007423 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007424 return (unsigned)getTypeSize(T);
7425}
7426
Abramo Bagnara13640492012-09-09 10:21:24 +00007427QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007428 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007429
7430 // Turn <4 x signed int> -> <4 x unsigned int>
7431 if (const VectorType *VTy = T->getAs<VectorType>())
7432 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007433 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007434
7435 // For enums, we return the unsigned version of the base type.
7436 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007437 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007438
7439 const BuiltinType *BTy = T->getAs<BuiltinType>();
7440 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007441 switch (BTy->getKind()) {
7442 case BuiltinType::Char_S:
7443 case BuiltinType::SChar:
7444 return UnsignedCharTy;
7445 case BuiltinType::Short:
7446 return UnsignedShortTy;
7447 case BuiltinType::Int:
7448 return UnsignedIntTy;
7449 case BuiltinType::Long:
7450 return UnsignedLongTy;
7451 case BuiltinType::LongLong:
7452 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007453 case BuiltinType::Int128:
7454 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007455 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007456 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007457 }
7458}
7459
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007460ASTMutationListener::~ASTMutationListener() { }
7461
Richard Smith1fa5d642013-05-11 05:45:24 +00007462void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7463 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007464
7465//===----------------------------------------------------------------------===//
7466// Builtin Type Computation
7467//===----------------------------------------------------------------------===//
7468
7469/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007470/// pointer over the consumed characters. This returns the resultant type. If
7471/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7472/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7473/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007474///
7475/// RequiresICE is filled in on return to indicate whether the value is required
7476/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007477static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007478 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007479 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007480 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007481 // Modifiers.
7482 int HowLong = 0;
7483 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007484 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007485
Chris Lattnerdc226c22010-10-01 22:42:38 +00007486 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007487 bool Done = false;
7488 while (!Done) {
7489 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007490 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007491 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007492 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007493 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007494 case 'S':
7495 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7496 assert(!Signed && "Can't use 'S' modifier multiple times!");
7497 Signed = true;
7498 break;
7499 case 'U':
7500 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7501 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7502 Unsigned = true;
7503 break;
7504 case 'L':
7505 assert(HowLong <= 2 && "Can't have LLLL modifier");
7506 ++HowLong;
7507 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007508 case 'W':
7509 // This modifier represents int64 type.
7510 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7511 switch (Context.getTargetInfo().getInt64Type()) {
7512 default:
7513 llvm_unreachable("Unexpected integer type");
7514 case TargetInfo::SignedLong:
7515 HowLong = 1;
7516 break;
7517 case TargetInfo::SignedLongLong:
7518 HowLong = 2;
7519 break;
7520 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007521 }
7522 }
7523
7524 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007525
Chris Lattnerecd79c62009-06-14 00:45:47 +00007526 // Read the base type.
7527 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007528 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007529 case 'v':
7530 assert(HowLong == 0 && !Signed && !Unsigned &&
7531 "Bad modifiers used with 'v'!");
7532 Type = Context.VoidTy;
7533 break;
Jack Carter24bef982013-08-15 15:16:57 +00007534 case 'h':
7535 assert(HowLong == 0 && !Signed && !Unsigned &&
7536 "Bad modifiers used with 'f'!");
7537 Type = Context.HalfTy;
7538 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007539 case 'f':
7540 assert(HowLong == 0 && !Signed && !Unsigned &&
7541 "Bad modifiers used with 'f'!");
7542 Type = Context.FloatTy;
7543 break;
7544 case 'd':
7545 assert(HowLong < 2 && !Signed && !Unsigned &&
7546 "Bad modifiers used with 'd'!");
7547 if (HowLong)
7548 Type = Context.LongDoubleTy;
7549 else
7550 Type = Context.DoubleTy;
7551 break;
7552 case 's':
7553 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7554 if (Unsigned)
7555 Type = Context.UnsignedShortTy;
7556 else
7557 Type = Context.ShortTy;
7558 break;
7559 case 'i':
7560 if (HowLong == 3)
7561 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7562 else if (HowLong == 2)
7563 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7564 else if (HowLong == 1)
7565 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7566 else
7567 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7568 break;
7569 case 'c':
7570 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7571 if (Signed)
7572 Type = Context.SignedCharTy;
7573 else if (Unsigned)
7574 Type = Context.UnsignedCharTy;
7575 else
7576 Type = Context.CharTy;
7577 break;
7578 case 'b': // boolean
7579 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7580 Type = Context.BoolTy;
7581 break;
7582 case 'z': // size_t.
7583 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7584 Type = Context.getSizeType();
7585 break;
7586 case 'F':
7587 Type = Context.getCFConstantStringType();
7588 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007589 case 'G':
7590 Type = Context.getObjCIdType();
7591 break;
7592 case 'H':
7593 Type = Context.getObjCSelType();
7594 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007595 case 'M':
7596 Type = Context.getObjCSuperType();
7597 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007598 case 'a':
7599 Type = Context.getBuiltinVaListType();
7600 assert(!Type.isNull() && "builtin va list type not initialized!");
7601 break;
7602 case 'A':
7603 // This is a "reference" to a va_list; however, what exactly
7604 // this means depends on how va_list is defined. There are two
7605 // different kinds of va_list: ones passed by value, and ones
7606 // passed by reference. An example of a by-value va_list is
7607 // x86, where va_list is a char*. An example of by-ref va_list
7608 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7609 // we want this argument to be a char*&; for x86-64, we want
7610 // it to be a __va_list_tag*.
7611 Type = Context.getBuiltinVaListType();
7612 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007613 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007614 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007615 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007616 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007617 break;
7618 case 'V': {
7619 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007620 unsigned NumElements = strtoul(Str, &End, 10);
7621 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007622 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007623
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007624 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7625 RequiresICE, false);
7626 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007627
7628 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007629 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007630 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007631 break;
7632 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007633 case 'E': {
7634 char *End;
7635
7636 unsigned NumElements = strtoul(Str, &End, 10);
7637 assert(End != Str && "Missing vector size");
7638
7639 Str = End;
7640
7641 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7642 false);
7643 Type = Context.getExtVectorType(ElementType, NumElements);
7644 break;
7645 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007646 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007647 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7648 false);
7649 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007650 Type = Context.getComplexType(ElementType);
7651 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007652 }
7653 case 'Y' : {
7654 Type = Context.getPointerDiffType();
7655 break;
7656 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007657 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007658 Type = Context.getFILEType();
7659 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007660 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007661 return QualType();
7662 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007663 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007664 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007665 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007666 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007667 else
7668 Type = Context.getjmp_bufType();
7669
Mike Stump2adb4da2009-07-28 23:47:15 +00007670 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007671 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007672 return QualType();
7673 }
7674 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007675 case 'K':
7676 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7677 Type = Context.getucontext_tType();
7678
7679 if (Type.isNull()) {
7680 Error = ASTContext::GE_Missing_ucontext;
7681 return QualType();
7682 }
7683 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007684 case 'p':
7685 Type = Context.getProcessIDType();
7686 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007687 }
Mike Stump11289f42009-09-09 15:08:12 +00007688
Chris Lattnerdc226c22010-10-01 22:42:38 +00007689 // If there are modifiers and if we're allowed to parse them, go for it.
7690 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007691 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007692 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007693 default: Done = true; --Str; break;
7694 case '*':
7695 case '&': {
7696 // Both pointers and references can have their pointee types
7697 // qualified with an address space.
7698 char *End;
7699 unsigned AddrSpace = strtoul(Str, &End, 10);
7700 if (End != Str && AddrSpace != 0) {
7701 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7702 Str = End;
7703 }
7704 if (c == '*')
7705 Type = Context.getPointerType(Type);
7706 else
7707 Type = Context.getLValueReferenceType(Type);
7708 break;
7709 }
7710 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7711 case 'C':
7712 Type = Type.withConst();
7713 break;
7714 case 'D':
7715 Type = Context.getVolatileType(Type);
7716 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007717 case 'R':
7718 Type = Type.withRestrict();
7719 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007720 }
7721 }
Chris Lattner84733392010-10-01 07:13:18 +00007722
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007723 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007724 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007725
Chris Lattnerecd79c62009-06-14 00:45:47 +00007726 return Type;
7727}
7728
7729/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007730QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007731 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007732 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007733 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007734
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007735 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007736
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007737 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007738 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007739 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7740 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007741 if (Error != GE_None)
7742 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007743
7744 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7745
Chris Lattnerecd79c62009-06-14 00:45:47 +00007746 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007747 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007748 if (Error != GE_None)
7749 return QualType();
7750
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007751 // If this argument is required to be an IntegerConstantExpression and the
7752 // caller cares, fill in the bitmask we return.
7753 if (RequiresICE && IntegerConstantArgs)
7754 *IntegerConstantArgs |= 1 << ArgTypes.size();
7755
Chris Lattnerecd79c62009-06-14 00:45:47 +00007756 // Do array -> pointer decay. The builtin should use the decayed type.
7757 if (Ty->isArrayType())
7758 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007759
Chris Lattnerecd79c62009-06-14 00:45:47 +00007760 ArgTypes.push_back(Ty);
7761 }
7762
7763 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7764 "'.' should only occur at end of builtin type list!");
7765
Reid Kleckner78af0702013-08-27 23:08:25 +00007766 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007767 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7768
7769 bool Variadic = (TypeStr[0] == '.');
7770
7771 // We really shouldn't be making a no-proto type here, especially in C++.
7772 if (ArgTypes.empty() && Variadic)
7773 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007774
John McCalldb40c7f2010-12-14 08:05:40 +00007775 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007776 EPI.ExtInfo = EI;
7777 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007778
Jordan Rose5c382722013-03-08 21:51:21 +00007779 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007780}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007781
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007782GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007783 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007784 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007785
Rafael Espindola3ae00052013-05-13 00:12:11 +00007786 GVALinkage External = GVA_StrongExternal;
7787 switch (FD->getTemplateSpecializationKind()) {
7788 case TSK_Undeclared:
7789 case TSK_ExplicitSpecialization:
7790 External = GVA_StrongExternal;
7791 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007792
Rafael Espindola3ae00052013-05-13 00:12:11 +00007793 case TSK_ExplicitInstantiationDefinition:
7794 return GVA_ExplicitTemplateInstantiation;
7795
7796 case TSK_ExplicitInstantiationDeclaration:
7797 case TSK_ImplicitInstantiation:
7798 External = GVA_TemplateInstantiation;
7799 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007800 }
7801
7802 if (!FD->isInlined())
7803 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007804
Alp Tokerbfa39342014-01-14 12:51:41 +00007805 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007806 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007807 // GNU or C99 inline semantics. Determine whether this symbol should be
7808 // externally visible.
7809 if (FD->isInlineDefinitionExternallyVisible())
7810 return External;
7811
7812 // C99 inline semantics, where the symbol is not externally visible.
7813 return GVA_C99Inline;
7814 }
7815
7816 // C++0x [temp.explicit]p9:
7817 // [ Note: The intent is that an inline function that is the subject of
7818 // an explicit instantiation declaration will still be implicitly
7819 // instantiated when used so that the body can be considered for
7820 // inlining, but that no out-of-line copy of the inline function would be
7821 // generated in the translation unit. -- end note ]
7822 if (FD->getTemplateSpecializationKind()
7823 == TSK_ExplicitInstantiationDeclaration)
7824 return GVA_C99Inline;
7825
7826 return GVA_CXXInline;
7827}
7828
7829GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007830 if (!VD->isExternallyVisible())
7831 return GVA_Internal;
7832
Richard Smith8809a0c2013-09-27 20:14:12 +00007833 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007834 case TSK_Undeclared:
7835 case TSK_ExplicitSpecialization:
7836 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007837
Rafael Espindola3ae00052013-05-13 00:12:11 +00007838 case TSK_ExplicitInstantiationDeclaration:
7839 llvm_unreachable("Variable should not be instantiated");
7840 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007841
Rafael Espindola3ae00052013-05-13 00:12:11 +00007842 case TSK_ExplicitInstantiationDefinition:
7843 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007844
Rafael Espindola3ae00052013-05-13 00:12:11 +00007845 case TSK_ImplicitInstantiation:
7846 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007847 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007848
7849 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007850}
7851
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007852bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007853 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7854 if (!VD->isFileVarDecl())
7855 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007856 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7857 // We never need to emit an uninstantiated function template.
7858 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7859 return false;
7860 } else
7861 return false;
7862
7863 // If this is a member of a class template, we do not need to emit it.
7864 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007865 return false;
7866
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007867 // Weak references don't produce any output by themselves.
7868 if (D->hasAttr<WeakRefAttr>())
7869 return false;
7870
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007871 // Aliases and used decls are required.
7872 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7873 return true;
7874
7875 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7876 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007877 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007878 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007879
7880 // Constructors and destructors are required.
7881 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7882 return true;
7883
John McCall6bd2a892013-01-25 22:31:03 +00007884 // The key function for a class is required. This rule only comes
7885 // into play when inline functions can be key functions, though.
7886 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7887 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7888 const CXXRecordDecl *RD = MD->getParent();
7889 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7890 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7891 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7892 return true;
7893 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007894 }
7895 }
7896
7897 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7898
7899 // static, static inline, always_inline, and extern inline functions can
7900 // always be deferred. Normal inline functions can be deferred in C99/C++.
7901 // Implicit template instantiations can also be deferred in C++.
7902 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007903 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007904 return false;
7905 return true;
7906 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007907
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007908 const VarDecl *VD = cast<VarDecl>(D);
7909 assert(VD->isFileVarDecl() && "Expected file scoped var");
7910
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007911 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7912 return false;
7913
Richard Smitha0e5e542012-11-12 21:38:00 +00007914 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007915 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007916 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7917 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007918
Richard Smitha0e5e542012-11-12 21:38:00 +00007919 // Variables that have destruction with side-effects are required.
7920 if (VD->getType().isDestructedType())
7921 return true;
7922
7923 // Variables that have initialization with side-effects are required.
7924 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7925 return true;
7926
7927 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007928}
Charles Davis53c59df2010-08-16 03:33:14 +00007929
Reid Kleckner78af0702013-08-27 23:08:25 +00007930CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7931 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007932 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007933 if (IsCXXMethod)
7934 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007935
Reid Kleckner78af0702013-08-27 23:08:25 +00007936 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007937}
7938
Jay Foad39c79802011-01-12 09:06:06 +00007939bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007940 // Pass through to the C++ ABI object
7941 return ABI->isNearlyEmpty(RD);
7942}
7943
Reid Kleckner96f8f932014-02-05 17:27:08 +00007944VTableContextBase *ASTContext::getVTableContext() {
7945 if (!VTContext.get()) {
7946 if (Target->getCXXABI().isMicrosoft())
7947 VTContext.reset(new MicrosoftVTableContext(*this));
7948 else
7949 VTContext.reset(new ItaniumVTableContext(*this));
7950 }
7951 return VTContext.get();
7952}
7953
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007954MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007955 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007956 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007957 case TargetCXXABI::GenericItanium:
7958 case TargetCXXABI::GenericARM:
7959 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007960 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007961 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007962 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007963 }
David Blaikie83d382b2011-09-23 05:06:16 +00007964 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007965}
7966
Charles Davis53c59df2010-08-16 03:33:14 +00007967CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007968
7969size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007970 return ASTRecordLayouts.getMemorySize() +
7971 llvm::capacity_in_bytes(ObjCLayouts) +
7972 llvm::capacity_in_bytes(KeyFunctions) +
7973 llvm::capacity_in_bytes(ObjCImpls) +
7974 llvm::capacity_in_bytes(BlockVarCopyInits) +
7975 llvm::capacity_in_bytes(DeclAttrs) +
7976 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7977 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7978 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7979 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7980 llvm::capacity_in_bytes(OverriddenMethods) +
7981 llvm::capacity_in_bytes(Types) +
7982 llvm::capacity_in_bytes(VariableArrayTypes) +
7983 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007984}
Ted Kremenek540017e2011-10-06 05:00:56 +00007985
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007986/// getIntTypeForBitwidth -
7987/// sets integer QualTy according to specified details:
7988/// bitwidth, signed/unsigned.
7989/// Returns empty type if there is no appropriate target types.
7990QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7991 unsigned Signed) const {
7992 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7993 CanQualType QualTy = getFromTargetType(Ty);
7994 if (!QualTy && DestWidth == 128)
7995 return Signed ? Int128Ty : UnsignedInt128Ty;
7996 return QualTy;
7997}
7998
7999/// getRealTypeForBitwidth -
8000/// sets floating point QualTy according to specified bitwidth.
8001/// Returns empty type if there is no appropriate target types.
8002QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8003 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8004 switch (Ty) {
8005 case TargetInfo::Float:
8006 return FloatTy;
8007 case TargetInfo::Double:
8008 return DoubleTy;
8009 case TargetInfo::LongDouble:
8010 return LongDoubleTy;
8011 case TargetInfo::NoFloat:
8012 return QualType();
8013 }
8014
8015 llvm_unreachable("Unhandled TargetInfo::RealType value");
8016}
8017
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008018void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8019 if (Number > 1)
8020 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008021}
8022
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008023unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8024 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8025 MangleNumbers.find(ND);
8026 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008027}
8028
David Majnemer2206bf52014-03-05 08:57:59 +00008029void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8030 if (Number > 1)
8031 StaticLocalNumbers[VD] = Number;
8032}
8033
8034unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8035 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8036 StaticLocalNumbers.find(VD);
8037 return I != StaticLocalNumbers.end() ? I->second : 1;
8038}
8039
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008040MangleNumberingContext &
8041ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008042 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8043 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8044 if (!MCtx)
8045 MCtx = createMangleNumberingContext();
8046 return *MCtx;
8047}
8048
8049MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8050 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008051}
8052
Ted Kremenek540017e2011-10-06 05:00:56 +00008053void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8054 ParamIndices[D] = index;
8055}
8056
8057unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8058 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8059 assert(I != ParamIndices.end() &&
8060 "ParmIndices lacks entry set by ParmVarDecl");
8061 return I->second;
8062}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008063
Richard Smithe6c01442013-06-05 00:46:14 +00008064APValue *
8065ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8066 bool MayCreate) {
8067 assert(E && E->getStorageDuration() == SD_Static &&
8068 "don't need to cache the computed value for this temporary");
8069 if (MayCreate)
8070 return &MaterializedTemporaryValues[E];
8071
8072 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8073 MaterializedTemporaryValues.find(E);
8074 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8075}
8076
Fariborz Jahanian615de762013-05-28 17:37:39 +00008077bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8078 const llvm::Triple &T = getTargetInfo().getTriple();
8079 if (!T.isOSDarwin())
8080 return false;
8081
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008082 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8083 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8084 return false;
8085
Fariborz Jahanian615de762013-05-28 17:37:39 +00008086 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8087 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8088 uint64_t Size = sizeChars.getQuantity();
8089 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8090 unsigned Align = alignChars.getQuantity();
8091 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8092 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8093}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008094
8095namespace {
8096
8097 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8098 /// parents as defined by the \c RecursiveASTVisitor.
8099 ///
8100 /// Note that the relationship described here is purely in terms of AST
8101 /// traversal - there are other relationships (for example declaration context)
8102 /// in the AST that are better modeled by special matchers.
8103 ///
8104 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8105 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8106
8107 public:
8108 /// \brief Builds and returns the translation unit's parent map.
8109 ///
8110 /// The caller takes ownership of the returned \c ParentMap.
8111 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8112 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8113 Visitor.TraverseDecl(&TU);
8114 return Visitor.Parents;
8115 }
8116
8117 private:
8118 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8119
8120 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8121 }
8122
8123 bool shouldVisitTemplateInstantiations() const {
8124 return true;
8125 }
8126 bool shouldVisitImplicitCode() const {
8127 return true;
8128 }
8129 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8130 // are not triggered during data recursion.
8131 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8132 return false;
8133 }
8134
8135 template <typename T>
8136 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8137 if (Node == NULL)
8138 return true;
8139 if (ParentStack.size() > 0)
8140 // FIXME: Currently we add the same parent multiple times, for example
8141 // when we visit all subexpressions of template instantiations; this is
8142 // suboptimal, bug benign: the only way to visit those is with
8143 // hasAncestor / hasParent, and those do not create new matches.
8144 // The plan is to enable DynTypedNode to be storable in a map or hash
8145 // map. The main problem there is to implement hash functions /
8146 // comparison operators for all types that DynTypedNode supports that
8147 // do not have pointer identity.
8148 (*Parents)[Node].push_back(ParentStack.back());
8149 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8150 bool Result = (this ->* traverse) (Node);
8151 ParentStack.pop_back();
8152 return Result;
8153 }
8154
8155 bool TraverseDecl(Decl *DeclNode) {
8156 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8157 }
8158
8159 bool TraverseStmt(Stmt *StmtNode) {
8160 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8161 }
8162
8163 ASTContext::ParentMap *Parents;
8164 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8165
8166 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8167 };
8168
8169} // end namespace
8170
8171ASTContext::ParentVector
8172ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8173 assert(Node.getMemoizationData() &&
8174 "Invariant broken: only nodes that support memoization may be "
8175 "used in the parent map.");
8176 if (!AllParents) {
8177 // We always need to run over the whole translation unit, as
8178 // hasAncestor can escape any subtree.
8179 AllParents.reset(
8180 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8181 }
8182 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8183 if (I == AllParents->end()) {
8184 return ParentVector();
8185 }
8186 return I->second;
8187}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008188
8189bool
8190ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8191 const ObjCMethodDecl *MethodImpl) {
8192 // No point trying to match an unavailable/deprecated mothod.
8193 if (MethodDecl->hasAttr<UnavailableAttr>()
8194 || MethodDecl->hasAttr<DeprecatedAttr>())
8195 return false;
8196 if (MethodDecl->getObjCDeclQualifier() !=
8197 MethodImpl->getObjCDeclQualifier())
8198 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008199 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008200 return false;
8201
8202 if (MethodDecl->param_size() != MethodImpl->param_size())
8203 return false;
8204
8205 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8206 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8207 EF = MethodDecl->param_end();
8208 IM != EM && IF != EF; ++IM, ++IF) {
8209 const ParmVarDecl *DeclVar = (*IF);
8210 const ParmVarDecl *ImplVar = (*IM);
8211 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8212 return false;
8213 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8214 return false;
8215 }
8216 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8217
8218}