blob: 97fb50c746fd49d3c00e1a3784c39b403d41927c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000038#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000039
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
Douglas Gregor18274032010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000057};
58
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
88 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
89 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
90 return NULL;
91 }
92
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000093 // TODO: handle comments for function parameters properly.
94 if (isa<ParmVarDecl>(D))
95 return NULL;
96
Dmitri Gribenko96b09862012-07-31 22:37:06 +000097 // TODO: we could look up template parameter documentation in the template
98 // documentation.
99 if (isa<TemplateTypeParmDecl>(D) ||
100 isa<NonTypeTemplateParmDecl>(D) ||
101 isa<TemplateTemplateParmDecl>(D))
102 return NULL;
103
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000104 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000105
106 // If there are no comments anywhere, we won't find anything.
107 if (RawComments.empty())
108 return NULL;
109
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000110 // Find declaration location.
111 // For Objective-C declarations we generally don't expect to have multiple
112 // declarators, thus use declaration starting location as the "declaration
113 // location".
114 // For all other declarations multiple declarators are used quite frequently,
115 // so we use the location of the identifier as the "declaration location".
116 SourceLocation DeclLoc;
117 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000118 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000119 isa<RedeclarableTemplateDecl>(D) ||
120 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000121 DeclLoc = D->getLocStart();
122 else
123 DeclLoc = D->getLocation();
124
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000125 // If the declaration doesn't map directly to a location in a file, we
126 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000127 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
128 return NULL;
129
130 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000131 ArrayRef<RawComment *>::iterator Comment;
132 {
133 // When searching for comments during parsing, the comment we are looking
134 // for is usually among the last two comments we parsed -- check them
135 // first.
136 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
137 BeforeThanCompare<RawComment> Compare(SourceMgr);
138 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
139 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
140 if (!Found && RawComments.size() >= 2) {
141 MaybeBeforeDecl--;
142 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
143 }
144
145 if (Found) {
146 Comment = MaybeBeforeDecl + 1;
147 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
148 &CommentAtDeclLoc, Compare));
149 } else {
150 // Slow path.
151 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
152 &CommentAtDeclLoc, Compare);
153 }
154 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000155
156 // Decompose the location for the declaration and find the beginning of the
157 // file buffer.
158 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
159
160 // First check whether we have a trailing comment.
161 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000162 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000163 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000164 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000166 // Check that Doxygen trailing comment comes after the declaration, starts
167 // on the same line and in the same file as the declaration.
168 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
169 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
170 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
171 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000172 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000173 }
174 }
175
176 // The comment just after the declaration was not a trailing comment.
177 // Let's look at the previous comment.
178 if (Comment == RawComments.begin())
179 return NULL;
180 --Comment;
181
182 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000183 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000184 return NULL;
185
186 // Decompose the end of the comment.
187 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000189
190 // If the comment and the declaration aren't in the same file, then they
191 // aren't related.
192 if (DeclLocDecomp.first != CommentEndDecomp.first)
193 return NULL;
194
195 // Get the corresponding buffer.
196 bool Invalid = false;
197 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
198 &Invalid).data();
199 if (Invalid)
200 return NULL;
201
202 // Extract text between the comment and declaration.
203 StringRef Text(Buffer + CommentEndDecomp.second,
204 DeclLocDecomp.second - CommentEndDecomp.second);
205
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000206 // There should be no other declarations or preprocessor directives between
207 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000208 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000209 return NULL;
210
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000211 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000212}
213
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000214namespace {
215/// If we have a 'templated' declaration for a template, adjust 'D' to
216/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000217/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000218const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000219 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000220 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000221 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000222 return FTD;
223
224 // Nothing to do if function is not an implicit instantiation.
225 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
226 return D;
227
228 // Function is an implicit instantiation of a function template?
229 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
230 return FTD;
231
232 // Function is instantiated from a member definition of a class template?
233 if (const FunctionDecl *MemberDecl =
234 FD->getInstantiatedFromMemberFunction())
235 return MemberDecl;
236
237 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000238 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000239 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
240 // Static data member is instantiated from a member definition of a class
241 // template?
242 if (VD->isStaticDataMember())
243 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
244 return MemberDecl;
245
246 return D;
247 }
248 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
249 // Is this class declaration part of a class template?
250 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
251 return CTD;
252
253 // Class is an implicit instantiation of a class template or partial
254 // specialization?
255 if (const ClassTemplateSpecializationDecl *CTSD =
256 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
257 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
258 return D;
259 llvm::PointerUnion<ClassTemplateDecl *,
260 ClassTemplatePartialSpecializationDecl *>
261 PU = CTSD->getSpecializedTemplateOrPartial();
262 return PU.is<ClassTemplateDecl*>() ?
263 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
264 static_cast<const Decl*>(
265 PU.get<ClassTemplatePartialSpecializationDecl *>());
266 }
267
268 // Class is instantiated from a member definition of a class template?
269 if (const MemberSpecializationInfo *Info =
270 CRD->getMemberSpecializationInfo())
271 return Info->getInstantiatedFrom();
272
273 return D;
274 }
275 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
276 // Enum is instantiated from a member definition of a class template?
277 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
278 return MemberDecl;
279
280 return D;
281 }
282 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000283 return D;
284}
285} // unnamed namespace
286
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000287const RawComment *ASTContext::getRawCommentForAnyRedecl(
288 const Decl *D,
289 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000290 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000291
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000292 // Check whether we have cached a comment for this declaration already.
293 {
294 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
295 RedeclComments.find(D);
296 if (Pos != RedeclComments.end()) {
297 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000298 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
299 if (OriginalDecl)
300 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000301 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000302 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000303 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000304 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000305
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000306 // Search for comments attached to declarations in the redeclaration chain.
307 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000308 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000309 for (Decl::redecl_iterator I = D->redecls_begin(),
310 E = D->redecls_end();
311 I != E; ++I) {
312 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
313 RedeclComments.find(*I);
314 if (Pos != RedeclComments.end()) {
315 const RawCommentAndCacheFlags &Raw = Pos->second;
316 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
317 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000318 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000319 break;
320 }
321 } else {
322 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000323 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000324 RawCommentAndCacheFlags Raw;
325 if (RC) {
326 Raw.setRaw(RC);
327 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
328 } else
329 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000330 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000331 RedeclComments[*I] = Raw;
332 if (RC)
333 break;
334 }
335 }
336
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000337 // If we found a comment, it should be a documentation comment.
338 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000339
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000340 if (OriginalDecl)
341 *OriginalDecl = OriginalDeclForRC;
342
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000343 // Update cache for every declaration in the redeclaration chain.
344 RawCommentAndCacheFlags Raw;
345 Raw.setRaw(RC);
346 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000347 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000348
349 for (Decl::redecl_iterator I = D->redecls_begin(),
350 E = D->redecls_end();
351 I != E; ++I) {
352 RawCommentAndCacheFlags &R = RedeclComments[*I];
353 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
354 R = Raw;
355 }
356
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000357 return RC;
358}
359
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000360static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
361 SmallVectorImpl<const NamedDecl *> &Redeclared) {
362 const DeclContext *DC = ObjCMethod->getDeclContext();
363 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
364 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
365 if (!ID)
366 return;
367 // Add redeclared method here.
368 for (const ObjCCategoryDecl *ClsExtDecl = ID->getFirstClassExtension();
369 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
370 if (ObjCMethodDecl *RedeclaredMethod =
371 ClsExtDecl->getMethod(ObjCMethod->getSelector(),
372 ObjCMethod->isInstanceMethod()))
373 Redeclared.push_back(RedeclaredMethod);
374 }
375 }
376}
377
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000378comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
379 const Decl *D) const {
380 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
381 ThisDeclInfo->CommentDecl = D;
382 ThisDeclInfo->IsFilled = false;
383 ThisDeclInfo->fill();
384 ThisDeclInfo->CommentDecl = FC->getDecl();
385 comments::FullComment *CFC =
386 new (*this) comments::FullComment(FC->getBlocks(),
387 ThisDeclInfo);
388 return CFC;
389
390}
391
Dmitri Gribenko19523542012-09-29 11:40:46 +0000392comments::FullComment *ASTContext::getCommentForDecl(
393 const Decl *D,
394 const Preprocessor *PP) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000395 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000396
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000397 const Decl *Canonical = D->getCanonicalDecl();
398 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
399 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000400
401 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000402 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000403 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000404 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000405 return CFC;
406 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000407 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000408 }
409
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000410 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000411
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000412 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000413 if (!RC) {
414 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000415 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000416 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000417 addRedeclaredMethods(OMD, Overridden);
418 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
419 for (unsigned i = 0, e = Overridden.size(); i < e; i++) {
420 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000421 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000422 return CFC;
423 }
424 }
425 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000426 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000427 }
428
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000429 // If the RawComment was attached to other redeclaration of this Decl, we
430 // should parse the comment in context of that other Decl. This is important
431 // because comments can contain references to parameter names which can be
432 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000433 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000434 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000435
Dmitri Gribenko19523542012-09-29 11:40:46 +0000436 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000437 ParsedComments[Canonical] = FC;
438 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000439}
440
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000441void
442ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
443 TemplateTemplateParmDecl *Parm) {
444 ID.AddInteger(Parm->getDepth());
445 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000446 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000447
448 TemplateParameterList *Params = Parm->getTemplateParameters();
449 ID.AddInteger(Params->size());
450 for (TemplateParameterList::const_iterator P = Params->begin(),
451 PEnd = Params->end();
452 P != PEnd; ++P) {
453 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
454 ID.AddInteger(0);
455 ID.AddBoolean(TTP->isParameterPack());
456 continue;
457 }
458
459 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
460 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000461 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000462 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000463 if (NTTP->isExpandedParameterPack()) {
464 ID.AddBoolean(true);
465 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000466 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
467 QualType T = NTTP->getExpansionType(I);
468 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
469 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000470 } else
471 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000472 continue;
473 }
474
475 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
476 ID.AddInteger(2);
477 Profile(ID, TTP);
478 }
479}
480
481TemplateTemplateParmDecl *
482ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000483 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000484 // Check if we already have a canonical template template parameter.
485 llvm::FoldingSetNodeID ID;
486 CanonicalTemplateTemplateParm::Profile(ID, TTP);
487 void *InsertPos = 0;
488 CanonicalTemplateTemplateParm *Canonical
489 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
490 if (Canonical)
491 return Canonical->getParam();
492
493 // Build a canonical template parameter list.
494 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000495 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000496 CanonParams.reserve(Params->size());
497 for (TemplateParameterList::const_iterator P = Params->begin(),
498 PEnd = Params->end();
499 P != PEnd; ++P) {
500 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
501 CanonParams.push_back(
502 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000503 SourceLocation(),
504 SourceLocation(),
505 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000506 TTP->getIndex(), 0, false,
507 TTP->isParameterPack()));
508 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000509 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
510 QualType T = getCanonicalType(NTTP->getType());
511 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
512 NonTypeTemplateParmDecl *Param;
513 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000514 SmallVector<QualType, 2> ExpandedTypes;
515 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000516 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
517 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
518 ExpandedTInfos.push_back(
519 getTrivialTypeSourceInfo(ExpandedTypes.back()));
520 }
521
522 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000523 SourceLocation(),
524 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000525 NTTP->getDepth(),
526 NTTP->getPosition(), 0,
527 T,
528 TInfo,
529 ExpandedTypes.data(),
530 ExpandedTypes.size(),
531 ExpandedTInfos.data());
532 } else {
533 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000534 SourceLocation(),
535 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000536 NTTP->getDepth(),
537 NTTP->getPosition(), 0,
538 T,
539 NTTP->isParameterPack(),
540 TInfo);
541 }
542 CanonParams.push_back(Param);
543
544 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000545 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
546 cast<TemplateTemplateParmDecl>(*P)));
547 }
548
549 TemplateTemplateParmDecl *CanonTTP
550 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
551 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000552 TTP->getPosition(),
553 TTP->isParameterPack(),
554 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000555 TemplateParameterList::Create(*this, SourceLocation(),
556 SourceLocation(),
557 CanonParams.data(),
558 CanonParams.size(),
559 SourceLocation()));
560
561 // Get the new insert position for the node we care about.
562 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
563 assert(Canonical == 0 && "Shouldn't be in the map!");
564 (void)Canonical;
565
566 // Create the canonical template template parameter entry.
567 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
568 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
569 return CanonTTP;
570}
571
Charles Davis071cc7d2010-08-16 03:33:14 +0000572CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000573 if (!LangOpts.CPlusPlus) return 0;
574
Charles Davis20cf7172010-08-19 02:18:14 +0000575 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000576 case CXXABI_ARM:
577 return CreateARMCXXABI(*this);
578 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000579 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000580 case CXXABI_Microsoft:
581 return CreateMicrosoftCXXABI(*this);
582 }
David Blaikie7530c032012-01-17 06:56:22 +0000583 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000584}
585
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000586static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000587 const LangOptions &LOpts) {
588 if (LOpts.FakeAddressSpaceMap) {
589 // The fake address space map must have a distinct entry for each
590 // language-specific address space.
591 static const unsigned FakeAddrSpaceMap[] = {
592 1, // opencl_global
593 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000594 3, // opencl_constant
595 4, // cuda_device
596 5, // cuda_constant
597 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000598 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000599 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000600 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000601 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000602 }
603}
604
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000605ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000606 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000607 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000608 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000609 unsigned size_reserve,
610 bool DelayInitialization)
611 : FunctionProtoTypes(this_()),
612 TemplateSpecializationTypes(this_()),
613 DependentTemplateSpecializationTypes(this_()),
614 SubstTemplateTemplateParmPacks(this_()),
615 GlobalNestedNameSpecifier(0),
616 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000617 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000618 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000619 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000620 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000621 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000622 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
623 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
624 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000625 NullTypeSourceInfo(QualType()),
626 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000627 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000628 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000629 Idents(idents), Selectors(sels),
630 BuiltinInfo(builtins),
631 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000632 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000633 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000634 CommentCommandTraits(BumpAlloc),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000635 LastSDM(0, 0),
636 UniqueBlockByRefTypeID(0)
637{
Mike Stump1eb44332009-09-09 15:08:12 +0000638 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000639 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000640
641 if (!DelayInitialization) {
642 assert(t && "No target supplied for ASTContext initialization");
643 InitBuiltinTypes(*t);
644 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000645}
646
Reid Spencer5f016e22007-07-11 17:01:13 +0000647ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000648 // Release the DenseMaps associated with DeclContext objects.
649 // FIXME: Is this the ideal solution?
650 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000651
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000652 // Call all of the deallocation functions.
653 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
654 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000655
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000656 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000657 // because they can contain DenseMaps.
658 for (llvm::DenseMap<const ObjCContainerDecl*,
659 const ASTRecordLayout*>::iterator
660 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
661 // Increment in loop to prevent using deallocated memory.
662 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
663 R->Destroy(*this);
664
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000665 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
666 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
667 // Increment in loop to prevent using deallocated memory.
668 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
669 R->Destroy(*this);
670 }
Douglas Gregor63200642010-08-30 16:49:28 +0000671
672 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
673 AEnd = DeclAttrs.end();
674 A != AEnd; ++A)
675 A->second->~AttrVec();
676}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000677
Douglas Gregor00545312010-05-23 18:26:36 +0000678void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
679 Deallocations.push_back(std::make_pair(Callback, Data));
680}
681
Mike Stump1eb44332009-09-09 15:08:12 +0000682void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000683ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000684 ExternalSource.reset(Source.take());
685}
686
Reid Spencer5f016e22007-07-11 17:01:13 +0000687void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000688 llvm::errs() << "\n*** AST Context Stats:\n";
689 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000690
Douglas Gregordbe833d2009-05-26 14:40:08 +0000691 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000692#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000693#define ABSTRACT_TYPE(Name, Parent)
694#include "clang/AST/TypeNodes.def"
695 0 // Extra
696 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000697
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
699 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000700 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 }
702
Douglas Gregordbe833d2009-05-26 14:40:08 +0000703 unsigned Idx = 0;
704 unsigned TotalBytes = 0;
705#define TYPE(Name, Parent) \
706 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000707 llvm::errs() << " " << counts[Idx] << " " << #Name \
708 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000709 TotalBytes += counts[Idx] * sizeof(Name##Type); \
710 ++Idx;
711#define ABSTRACT_TYPE(Name, Parent)
712#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chandler Carruthcd92a652011-07-04 05:32:14 +0000714 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
715
Douglas Gregor4923aa22010-07-02 20:37:36 +0000716 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000717 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
718 << NumImplicitDefaultConstructors
719 << " implicit default constructors created\n";
720 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
721 << NumImplicitCopyConstructors
722 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000723 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000724 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
725 << NumImplicitMoveConstructors
726 << " implicit move constructors created\n";
727 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
728 << NumImplicitCopyAssignmentOperators
729 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000730 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000731 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
732 << NumImplicitMoveAssignmentOperators
733 << " implicit move assignment operators created\n";
734 llvm::errs() << NumImplicitDestructorsDeclared << "/"
735 << NumImplicitDestructors
736 << " implicit destructors created\n";
737
Douglas Gregor2cf26342009-04-09 22:27:44 +0000738 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000739 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000740 ExternalSource->PrintStats();
741 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000742
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000743 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000744}
745
Douglas Gregor772eeae2011-08-12 06:49:56 +0000746TypedefDecl *ASTContext::getInt128Decl() const {
747 if (!Int128Decl) {
748 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
749 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
750 getTranslationUnitDecl(),
751 SourceLocation(),
752 SourceLocation(),
753 &Idents.get("__int128_t"),
754 TInfo);
755 }
756
757 return Int128Decl;
758}
759
760TypedefDecl *ASTContext::getUInt128Decl() const {
761 if (!UInt128Decl) {
762 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
763 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
764 getTranslationUnitDecl(),
765 SourceLocation(),
766 SourceLocation(),
767 &Idents.get("__uint128_t"),
768 TInfo);
769 }
770
771 return UInt128Decl;
772}
Reid Spencer5f016e22007-07-11 17:01:13 +0000773
John McCalle27ec8a2009-10-23 23:03:21 +0000774void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000775 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000776 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000777 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000778}
779
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000780void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
781 assert((!this->Target || this->Target == &Target) &&
782 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000785 this->Target = &Target;
786
787 ABI.reset(createCXXABI(Target));
788 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
789
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 // C99 6.2.5p19.
791 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 // C99 6.2.5p2.
794 InitBuiltinType(BoolTy, BuiltinType::Bool);
795 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000796 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000797 InitBuiltinType(CharTy, BuiltinType::Char_S);
798 else
799 InitBuiltinType(CharTy, BuiltinType::Char_U);
800 // C99 6.2.5p4.
801 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
802 InitBuiltinType(ShortTy, BuiltinType::Short);
803 InitBuiltinType(IntTy, BuiltinType::Int);
804 InitBuiltinType(LongTy, BuiltinType::Long);
805 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 // C99 6.2.5p6.
808 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
809 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
810 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
811 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
812 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 // C99 6.2.5p10.
815 InitBuiltinType(FloatTy, BuiltinType::Float);
816 InitBuiltinType(DoubleTy, BuiltinType::Double);
817 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000818
Chris Lattner2df9ced2009-04-30 02:43:43 +0000819 // GNU extension, 128-bit integers.
820 InitBuiltinType(Int128Ty, BuiltinType::Int128);
821 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
822
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000823 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000824 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000825 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
826 else // -fshort-wchar makes wchar_t be unsigned.
827 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000828 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000829 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000830
James Molloy392da482012-05-04 10:55:22 +0000831 WIntTy = getFromTargetType(Target.getWIntType());
832
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000833 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
834 InitBuiltinType(Char16Ty, BuiltinType::Char16);
835 else // C99
836 Char16Ty = getFromTargetType(Target.getChar16Type());
837
838 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
839 InitBuiltinType(Char32Ty, BuiltinType::Char32);
840 else // C99
841 Char32Ty = getFromTargetType(Target.getChar32Type());
842
Douglas Gregor898574e2008-12-05 23:32:09 +0000843 // Placeholder type for type-dependent expressions whose type is
844 // completely unknown. No code should ever check a type against
845 // DependentTy and users should never see it; however, it is here to
846 // help diagnose failures to properly check for type-dependent
847 // expressions.
848 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000849
John McCall2a984ca2010-10-12 00:20:44 +0000850 // Placeholder type for functions.
851 InitBuiltinType(OverloadTy, BuiltinType::Overload);
852
John McCall864c0412011-04-26 20:42:42 +0000853 // Placeholder type for bound members.
854 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
855
John McCall3c3b7f92011-10-25 17:37:35 +0000856 // Placeholder type for pseudo-objects.
857 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
858
John McCall1de4d4e2011-04-07 08:22:57 +0000859 // "any" type; useful for debugger-like clients.
860 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
861
John McCall0ddaeb92011-10-17 18:09:15 +0000862 // Placeholder type for unbridged ARC casts.
863 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
864
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000865 // Placeholder type for builtin functions.
866 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
867
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 // C99 6.2.5p11.
869 FloatComplexTy = getComplexType(FloatTy);
870 DoubleComplexTy = getComplexType(DoubleTy);
871 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000872
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000873 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000874 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
875 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000876 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000877
878 if (LangOpts.OpenCL) {
879 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
880 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
881 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
882 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
883 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
884 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
885 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000886
887 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000888 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
889 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000890
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000891 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000893 // void * type
894 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000895
896 // nullptr type (C++0x 2.14.7)
897 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000898
899 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
900 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000901
902 // Builtin type used to help define __builtin_va_list.
903 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000904}
905
David Blaikied6471f72011-09-25 23:23:43 +0000906DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000907 return SourceMgr.getDiagnostics();
908}
909
Douglas Gregor63200642010-08-30 16:49:28 +0000910AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
911 AttrVec *&Result = DeclAttrs[D];
912 if (!Result) {
913 void *Mem = Allocate(sizeof(AttrVec));
914 Result = new (Mem) AttrVec;
915 }
916
917 return *Result;
918}
919
920/// \brief Erase the attributes corresponding to the given declaration.
921void ASTContext::eraseDeclAttrs(const Decl *D) {
922 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
923 if (Pos != DeclAttrs.end()) {
924 Pos->second->~AttrVec();
925 DeclAttrs.erase(Pos);
926 }
927}
928
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000929MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000930ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000931 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000932 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000933 = InstantiatedFromStaticDataMember.find(Var);
934 if (Pos == InstantiatedFromStaticDataMember.end())
935 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Douglas Gregor7caa6822009-07-24 20:34:43 +0000937 return Pos->second;
938}
939
Mike Stump1eb44332009-09-09 15:08:12 +0000940void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000941ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000942 TemplateSpecializationKind TSK,
943 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000944 assert(Inst->isStaticDataMember() && "Not a static data member");
945 assert(Tmpl->isStaticDataMember() && "Not a static data member");
946 assert(!InstantiatedFromStaticDataMember[Inst] &&
947 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000948 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000949 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000950}
951
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000952FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
953 const FunctionDecl *FD){
954 assert(FD && "Specialization is 0");
955 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000956 = ClassScopeSpecializationPattern.find(FD);
957 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000958 return 0;
959
960 return Pos->second;
961}
962
963void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
964 FunctionDecl *Pattern) {
965 assert(FD && "Specialization is 0");
966 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000967 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000968}
969
John McCall7ba107a2009-11-18 02:36:19 +0000970NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000971ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000972 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000973 = InstantiatedFromUsingDecl.find(UUD);
974 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000975 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Anders Carlsson0d8df782009-08-29 19:37:28 +0000977 return Pos->second;
978}
979
980void
John McCalled976492009-12-04 22:46:56 +0000981ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
982 assert((isa<UsingDecl>(Pattern) ||
983 isa<UnresolvedUsingValueDecl>(Pattern) ||
984 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
985 "pattern decl is not a using decl");
986 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
987 InstantiatedFromUsingDecl[Inst] = Pattern;
988}
989
990UsingShadowDecl *
991ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
992 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
993 = InstantiatedFromUsingShadowDecl.find(Inst);
994 if (Pos == InstantiatedFromUsingShadowDecl.end())
995 return 0;
996
997 return Pos->second;
998}
999
1000void
1001ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1002 UsingShadowDecl *Pattern) {
1003 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1004 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001005}
1006
Anders Carlssond8b285f2009-09-01 04:26:58 +00001007FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1008 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1009 = InstantiatedFromUnnamedFieldDecl.find(Field);
1010 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1011 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Anders Carlssond8b285f2009-09-01 04:26:58 +00001013 return Pos->second;
1014}
1015
1016void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1017 FieldDecl *Tmpl) {
1018 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1019 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1020 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1021 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Anders Carlssond8b285f2009-09-01 04:26:58 +00001023 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1024}
1025
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001026bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1027 const FieldDecl *LastFD) const {
1028 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001029 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001030}
1031
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001032bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1033 const FieldDecl *LastFD) const {
1034 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001035 FD->getBitWidthValue(*this) == 0 &&
1036 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001037}
1038
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001039bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1040 const FieldDecl *LastFD) const {
1041 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001042 FD->getBitWidthValue(*this) &&
1043 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001044}
1045
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001046bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001047 const FieldDecl *LastFD) const {
1048 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001049 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001050}
1051
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001052bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001053 const FieldDecl *LastFD) const {
1054 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001055 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001056}
1057
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001058ASTContext::overridden_cxx_method_iterator
1059ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1060 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001061 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001062 if (Pos == OverriddenMethods.end())
1063 return 0;
1064
1065 return Pos->second.begin();
1066}
1067
1068ASTContext::overridden_cxx_method_iterator
1069ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1070 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001071 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001072 if (Pos == OverriddenMethods.end())
1073 return 0;
1074
1075 return Pos->second.end();
1076}
1077
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001078unsigned
1079ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1080 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001081 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001082 if (Pos == OverriddenMethods.end())
1083 return 0;
1084
1085 return Pos->second.size();
1086}
1087
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001088void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1089 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001090 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001091 OverriddenMethods[Method].push_back(Overridden);
1092}
1093
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001094void ASTContext::getOverriddenMethods(
1095 const NamedDecl *D,
1096 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001097 assert(D);
1098
1099 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001100 Overridden.append(CXXMethod->begin_overridden_methods(),
1101 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001102 return;
1103 }
1104
1105 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1106 if (!Method)
1107 return;
1108
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001109 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1110 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001111 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001112}
1113
Douglas Gregore6649772011-12-03 00:30:27 +00001114void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1115 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1116 assert(!Import->isFromASTFile() && "Non-local import declaration");
1117 if (!FirstLocalImport) {
1118 FirstLocalImport = Import;
1119 LastLocalImport = Import;
1120 return;
1121 }
1122
1123 LastLocalImport->NextLocalImport = Import;
1124 LastLocalImport = Import;
1125}
1126
Chris Lattner464175b2007-07-18 17:52:12 +00001127//===----------------------------------------------------------------------===//
1128// Type Sizing and Analysis
1129//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001130
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001131/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1132/// scalar floating point type.
1133const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001134 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001135 assert(BT && "Not a floating point type!");
1136 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001137 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001138 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001139 case BuiltinType::Float: return Target->getFloatFormat();
1140 case BuiltinType::Double: return Target->getDoubleFormat();
1141 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001142 }
1143}
1144
Ken Dyck8b752f12010-01-27 17:10:57 +00001145/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001146/// specified decl. Note that bitfields do not have a valid alignment, so
1147/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001148/// If @p RefAsPointee, references are treated like their underlying type
1149/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001150CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001151 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001152
John McCall4081a5c2010-10-08 18:24:19 +00001153 bool UseAlignAttrOnly = false;
1154 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1155 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001156
John McCall4081a5c2010-10-08 18:24:19 +00001157 // __attribute__((aligned)) can increase or decrease alignment
1158 // *except* on a struct or struct member, where it only increases
1159 // alignment unless 'packed' is also specified.
1160 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001161 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001162 // ignore that possibility; Sema should diagnose it.
1163 if (isa<FieldDecl>(D)) {
1164 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1165 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1166 } else {
1167 UseAlignAttrOnly = true;
1168 }
1169 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001170 else if (isa<FieldDecl>(D))
1171 UseAlignAttrOnly =
1172 D->hasAttr<PackedAttr>() ||
1173 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001174
John McCallba4f5d52011-01-20 07:57:12 +00001175 // If we're using the align attribute only, just ignore everything
1176 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001177 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001178 // do nothing
1179
John McCall4081a5c2010-10-08 18:24:19 +00001180 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001181 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001182 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001183 if (RefAsPointee)
1184 T = RT->getPointeeType();
1185 else
1186 T = getPointerType(RT->getPointeeType());
1187 }
1188 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001189 // Adjust alignments of declarations with array type by the
1190 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001191 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001192 const ArrayType *arrayType;
1193 if (MinWidth && (arrayType = getAsArrayType(T))) {
1194 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001195 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001196 else if (isa<ConstantArrayType>(arrayType) &&
1197 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001198 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001199
John McCall3b657512011-01-19 10:06:00 +00001200 // Walk through any array types while we're at it.
1201 T = getBaseElementType(arrayType);
1202 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001203 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001204 }
John McCallba4f5d52011-01-20 07:57:12 +00001205
1206 // Fields can be subject to extra alignment constraints, like if
1207 // the field is packed, the struct is packed, or the struct has a
1208 // a max-field-alignment constraint (#pragma pack). So calculate
1209 // the actual alignment of the field within the struct, and then
1210 // (as we're expected to) constrain that by the alignment of the type.
1211 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1212 // So calculate the alignment of the field.
1213 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1214
1215 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001216 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001217
1218 // Use the GCD of that and the offset within the record.
1219 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1220 if (offset > 0) {
1221 // Alignment is always a power of 2, so the GCD will be a power of 2,
1222 // which means we get to do this crazy thing instead of Euclid's.
1223 uint64_t lowBitOfOffset = offset & (~offset + 1);
1224 if (lowBitOfOffset < fieldAlign)
1225 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1226 }
1227
1228 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001229 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001230 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001231
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001232 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001233}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001234
John McCall929bbfb2012-08-21 04:10:00 +00001235// getTypeInfoDataSizeInChars - Return the size of a type, in
1236// chars. If the type is a record, its data size is returned. This is
1237// the size of the memcpy that's performed when assigning this type
1238// using a trivial copy/move assignment operator.
1239std::pair<CharUnits, CharUnits>
1240ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1241 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1242
1243 // In C++, objects can sometimes be allocated into the tail padding
1244 // of a base-class subobject. We decide whether that's possible
1245 // during class layout, so here we can just trust the layout results.
1246 if (getLangOpts().CPlusPlus) {
1247 if (const RecordType *RT = T->getAs<RecordType>()) {
1248 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1249 sizeAndAlign.first = layout.getDataSize();
1250 }
1251 }
1252
1253 return sizeAndAlign;
1254}
1255
John McCallea1471e2010-05-20 01:18:31 +00001256std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001257ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001258 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001259 return std::make_pair(toCharUnitsFromBits(Info.first),
1260 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001261}
1262
1263std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001264ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001265 return getTypeInfoInChars(T.getTypePtr());
1266}
1267
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001268std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1269 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1270 if (it != MemoizedTypeInfo.end())
1271 return it->second;
1272
1273 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1274 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1275 return Info;
1276}
1277
1278/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1279/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001280///
1281/// FIXME: Pointers into different addr spaces could have different sizes and
1282/// alignment requirements: getPointerInfo should take an AddrSpace, this
1283/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001284std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001285ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001286 uint64_t Width=0;
1287 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001288 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001289#define TYPE(Class, Base)
1290#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001291#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001292#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1293#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001294 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001295
Chris Lattner692233e2007-07-13 22:27:08 +00001296 case Type::FunctionNoProto:
1297 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001298 // GCC extension: alignof(function) = 32 bits
1299 Width = 0;
1300 Align = 32;
1301 break;
1302
Douglas Gregor72564e72009-02-26 23:50:07 +00001303 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001304 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001305 Width = 0;
1306 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1307 break;
1308
Steve Narofffb22d962007-08-30 01:06:46 +00001309 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001310 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Chris Lattner98be4942008-03-05 18:54:05 +00001312 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001313 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001314 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1315 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001316 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001317 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001318 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001319 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001320 }
Nate Begeman213541a2008-04-18 23:10:10 +00001321 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001322 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001323 const VectorType *VT = cast<VectorType>(T);
1324 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1325 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001326 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001327 // If the alignment is not a power of 2, round up to the next power of 2.
1328 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001329 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001330 Align = llvm::NextPowerOf2(Align);
1331 Width = llvm::RoundUpToAlignment(Width, Align);
1332 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001333 // Adjust the alignment based on the target max.
1334 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1335 if (TargetVectorAlign && TargetVectorAlign < Align)
1336 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001337 break;
1338 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001339
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001340 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001341 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001342 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001343 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001344 // GCC extension: alignof(void) = 8 bits.
1345 Width = 0;
1346 Align = 8;
1347 break;
1348
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001349 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001350 Width = Target->getBoolWidth();
1351 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001352 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001353 case BuiltinType::Char_S:
1354 case BuiltinType::Char_U:
1355 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001356 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001357 Width = Target->getCharWidth();
1358 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001359 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001360 case BuiltinType::WChar_S:
1361 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001362 Width = Target->getWCharWidth();
1363 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001364 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001365 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001366 Width = Target->getChar16Width();
1367 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001368 break;
1369 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001370 Width = Target->getChar32Width();
1371 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001372 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001373 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001374 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001375 Width = Target->getShortWidth();
1376 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001377 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001378 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001379 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001380 Width = Target->getIntWidth();
1381 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001382 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001383 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001384 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001385 Width = Target->getLongWidth();
1386 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001387 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001388 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001389 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001390 Width = Target->getLongLongWidth();
1391 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001392 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001393 case BuiltinType::Int128:
1394 case BuiltinType::UInt128:
1395 Width = 128;
1396 Align = 128; // int128_t is 128-bit aligned on all targets.
1397 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001398 case BuiltinType::Half:
1399 Width = Target->getHalfWidth();
1400 Align = Target->getHalfAlign();
1401 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001402 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001403 Width = Target->getFloatWidth();
1404 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001405 break;
1406 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001407 Width = Target->getDoubleWidth();
1408 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001409 break;
1410 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001411 Width = Target->getLongDoubleWidth();
1412 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001413 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001414 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001415 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1416 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001417 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001418 case BuiltinType::ObjCId:
1419 case BuiltinType::ObjCClass:
1420 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001421 Width = Target->getPointerWidth(0);
1422 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001423 break;
Guy Benyeib13621d2012-12-18 14:38:23 +00001424 case BuiltinType::OCLImage1d:
1425 case BuiltinType::OCLImage1dArray:
1426 case BuiltinType::OCLImage1dBuffer:
1427 case BuiltinType::OCLImage2d:
1428 case BuiltinType::OCLImage2dArray:
1429 case BuiltinType::OCLImage3d:
1430 // Currently these types are pointers to opaque types.
1431 Width = Target->getPointerWidth(0);
1432 Align = Target->getPointerAlign(0);
1433 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001434 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001435 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001436 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001437 Width = Target->getPointerWidth(0);
1438 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001439 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001440 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001441 unsigned AS = getTargetAddressSpace(
1442 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001443 Width = Target->getPointerWidth(AS);
1444 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001445 break;
1446 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001447 case Type::LValueReference:
1448 case Type::RValueReference: {
1449 // alignof and sizeof should never enter this code path here, so we go
1450 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001451 unsigned AS = getTargetAddressSpace(
1452 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001453 Width = Target->getPointerWidth(AS);
1454 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001455 break;
1456 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001457 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001458 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001459 Width = Target->getPointerWidth(AS);
1460 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001461 break;
1462 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001463 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001464 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001465 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001466 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001467 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001468 Align = PtrDiffInfo.second;
1469 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001470 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001471 case Type::Complex: {
1472 // Complex types have the same alignment as their elements, but twice the
1473 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001474 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001475 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001476 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001477 Align = EltInfo.second;
1478 break;
1479 }
John McCallc12c5bb2010-05-15 11:32:37 +00001480 case Type::ObjCObject:
1481 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001482 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001483 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001484 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001485 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001486 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001487 break;
1488 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001489 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001490 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001491 const TagType *TT = cast<TagType>(T);
1492
1493 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001494 Width = 8;
1495 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001496 break;
1497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Daniel Dunbar1d751182008-11-08 05:48:37 +00001499 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001500 return getTypeInfo(ET->getDecl()->getIntegerType());
1501
Daniel Dunbar1d751182008-11-08 05:48:37 +00001502 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001503 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001504 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001505 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001506 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001507 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001508
Chris Lattner9fcfe922009-10-22 05:17:15 +00001509 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001510 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1511 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001512
Richard Smith34b41d92011-02-20 03:19:35 +00001513 case Type::Auto: {
1514 const AutoType *A = cast<AutoType>(T);
1515 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001516 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001517 }
1518
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001519 case Type::Paren:
1520 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1521
Douglas Gregor18857642009-04-30 17:32:17 +00001522 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001523 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001524 std::pair<uint64_t, unsigned> Info
1525 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001526 // If the typedef has an aligned attribute on it, it overrides any computed
1527 // alignment we have. This violates the GCC documentation (which says that
1528 // attribute(aligned) can only round up) but matches its implementation.
1529 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1530 Align = AttrAlign;
1531 else
1532 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001533 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001534 break;
Chris Lattner71763312008-04-06 22:05:18 +00001535 }
Douglas Gregor18857642009-04-30 17:32:17 +00001536
1537 case Type::TypeOfExpr:
1538 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1539 .getTypePtr());
1540
1541 case Type::TypeOf:
1542 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1543
Anders Carlsson395b4752009-06-24 19:06:50 +00001544 case Type::Decltype:
1545 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1546 .getTypePtr());
1547
Sean Huntca63c202011-05-24 22:41:36 +00001548 case Type::UnaryTransform:
1549 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1550
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001551 case Type::Elaborated:
1552 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001553
John McCall9d156a72011-01-06 01:58:22 +00001554 case Type::Attributed:
1555 return getTypeInfo(
1556 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1557
Richard Smith3e4c6c42011-05-05 21:57:07 +00001558 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001559 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001560 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001561 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1562 // A type alias template specialization may refer to a typedef with the
1563 // aligned attribute on it.
1564 if (TST->isTypeAlias())
1565 return getTypeInfo(TST->getAliasedType().getTypePtr());
1566 else
1567 return getTypeInfo(getCanonicalType(T));
1568 }
1569
Eli Friedmanb001de72011-10-06 23:00:33 +00001570 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001571 std::pair<uint64_t, unsigned> Info
1572 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1573 Width = Info.first;
1574 Align = Info.second;
1575 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1576 llvm::isPowerOf2_64(Width)) {
1577 // We can potentially perform lock-free atomic operations for this
1578 // type; promote the alignment appropriately.
1579 // FIXME: We could potentially promote the width here as well...
1580 // is that worthwhile? (Non-struct atomic types generally have
1581 // power-of-two size anyway, but structs might not. Requires a bit
1582 // of implementation work to make sure we zero out the extra bits.)
1583 Align = static_cast<unsigned>(Width);
1584 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001585 }
1586
Douglas Gregor18857642009-04-30 17:32:17 +00001587 }
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Eli Friedman2be46072011-10-14 20:59:01 +00001589 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001590 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001591}
1592
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001593/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1594CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1595 return CharUnits::fromQuantity(BitSize / getCharWidth());
1596}
1597
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001598/// toBits - Convert a size in characters to a size in characters.
1599int64_t ASTContext::toBits(CharUnits CharSize) const {
1600 return CharSize.getQuantity() * getCharWidth();
1601}
1602
Ken Dyckbdc601b2009-12-22 14:23:30 +00001603/// getTypeSizeInChars - Return the size of the specified type, in characters.
1604/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001605CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001606 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001607}
Jay Foad4ba2a172011-01-12 09:06:06 +00001608CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001609 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001610}
1611
Ken Dyck16e20cc2010-01-26 17:25:18 +00001612/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001613/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001614CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001615 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001616}
Jay Foad4ba2a172011-01-12 09:06:06 +00001617CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001618 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001619}
1620
Chris Lattner34ebde42009-01-27 18:08:34 +00001621/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1622/// type for the current target in bits. This can be different than the ABI
1623/// alignment in cases where it is beneficial for performance to overalign
1624/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001625unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001626 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001627
1628 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001629 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001630 T = CT->getElementType().getTypePtr();
1631 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001632 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1633 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001634 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1635
Chris Lattner34ebde42009-01-27 18:08:34 +00001636 return ABIAlign;
1637}
1638
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001639/// DeepCollectObjCIvars -
1640/// This routine first collects all declared, but not synthesized, ivars in
1641/// super class and then collects all ivars, including those synthesized for
1642/// current class. This routine is used for implementation of current class
1643/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001644///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001645void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1646 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001647 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001648 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1649 DeepCollectObjCIvars(SuperClass, false, Ivars);
1650 if (!leafClass) {
1651 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1652 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001653 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001654 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001655 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001656 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001657 Iv= Iv->getNextIvar())
1658 Ivars.push_back(Iv);
1659 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001660}
1661
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001662/// CollectInheritedProtocols - Collect all protocols in current class and
1663/// those inherited by it.
1664void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001665 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001666 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001667 // We can use protocol_iterator here instead of
1668 // all_referenced_protocol_iterator since we are walking all categories.
1669 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1670 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001671 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001672 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001673 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001674 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001675 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001676 CollectInheritedProtocols(*P, Protocols);
1677 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001678 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001679
1680 // Categories of this Interface.
1681 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1682 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1683 CollectInheritedProtocols(CDeclChain, Protocols);
1684 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1685 while (SD) {
1686 CollectInheritedProtocols(SD, Protocols);
1687 SD = SD->getSuperClass();
1688 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001689 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001690 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001691 PE = OC->protocol_end(); P != PE; ++P) {
1692 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001693 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001694 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1695 PE = Proto->protocol_end(); P != PE; ++P)
1696 CollectInheritedProtocols(*P, Protocols);
1697 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001698 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001699 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1700 PE = OP->protocol_end(); P != PE; ++P) {
1701 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001702 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001703 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1704 PE = Proto->protocol_end(); P != PE; ++P)
1705 CollectInheritedProtocols(*P, Protocols);
1706 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001707 }
1708}
1709
Jay Foad4ba2a172011-01-12 09:06:06 +00001710unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001711 unsigned count = 0;
1712 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001713 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1714 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001715 count += CDecl->ivar_size();
1716
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001717 // Count ivar defined in this class's implementation. This
1718 // includes synthesized ivars.
1719 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001720 count += ImplDecl->ivar_size();
1721
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001722 return count;
1723}
1724
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001725bool ASTContext::isSentinelNullExpr(const Expr *E) {
1726 if (!E)
1727 return false;
1728
1729 // nullptr_t is always treated as null.
1730 if (E->getType()->isNullPtrType()) return true;
1731
1732 if (E->getType()->isAnyPointerType() &&
1733 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1734 Expr::NPC_ValueDependentIsNull))
1735 return true;
1736
1737 // Unfortunately, __null has type 'int'.
1738 if (isa<GNUNullExpr>(E)) return true;
1739
1740 return false;
1741}
1742
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001743/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1744ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1745 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1746 I = ObjCImpls.find(D);
1747 if (I != ObjCImpls.end())
1748 return cast<ObjCImplementationDecl>(I->second);
1749 return 0;
1750}
1751/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1752ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1753 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1754 I = ObjCImpls.find(D);
1755 if (I != ObjCImpls.end())
1756 return cast<ObjCCategoryImplDecl>(I->second);
1757 return 0;
1758}
1759
1760/// \brief Set the implementation of ObjCInterfaceDecl.
1761void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1762 ObjCImplementationDecl *ImplD) {
1763 assert(IFaceD && ImplD && "Passed null params");
1764 ObjCImpls[IFaceD] = ImplD;
1765}
1766/// \brief Set the implementation of ObjCCategoryDecl.
1767void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1768 ObjCCategoryImplDecl *ImplD) {
1769 assert(CatD && ImplD && "Passed null params");
1770 ObjCImpls[CatD] = ImplD;
1771}
1772
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001773ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1774 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1775 return ID;
1776 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1777 return CD->getClassInterface();
1778 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1779 return IMD->getClassInterface();
1780
1781 return 0;
1782}
1783
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001784/// \brief Get the copy initialization expression of VarDecl,or NULL if
1785/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001786Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001787 assert(VD && "Passed null params");
1788 assert(VD->hasAttr<BlocksAttr>() &&
1789 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001790 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001791 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001792 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1793}
1794
1795/// \brief Set the copy inialization expression of a block var decl.
1796void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1797 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001798 assert(VD->hasAttr<BlocksAttr>() &&
1799 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001800 BlockVarCopyInits[VD] = Init;
1801}
1802
John McCalla93c9342009-12-07 02:54:59 +00001803TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001804 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001805 if (!DataSize)
1806 DataSize = TypeLoc::getFullDataSizeForType(T);
1807 else
1808 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001809 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001810
John McCalla93c9342009-12-07 02:54:59 +00001811 TypeSourceInfo *TInfo =
1812 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1813 new (TInfo) TypeSourceInfo(T);
1814 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001815}
1816
John McCalla93c9342009-12-07 02:54:59 +00001817TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001818 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001819 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001820 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001821 return DI;
1822}
1823
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001824const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001825ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001826 return getObjCLayout(D, 0);
1827}
1828
1829const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001830ASTContext::getASTObjCImplementationLayout(
1831 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001832 return getObjCLayout(D->getClassInterface(), D);
1833}
1834
Chris Lattnera7674d82007-07-13 22:13:22 +00001835//===----------------------------------------------------------------------===//
1836// Type creation/memoization methods
1837//===----------------------------------------------------------------------===//
1838
Jay Foad4ba2a172011-01-12 09:06:06 +00001839QualType
John McCall3b657512011-01-19 10:06:00 +00001840ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1841 unsigned fastQuals = quals.getFastQualifiers();
1842 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001843
1844 // Check if we've already instantiated this type.
1845 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001846 ExtQuals::Profile(ID, baseType, quals);
1847 void *insertPos = 0;
1848 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1849 assert(eq->getQualifiers() == quals);
1850 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001851 }
1852
John McCall3b657512011-01-19 10:06:00 +00001853 // If the base type is not canonical, make the appropriate canonical type.
1854 QualType canon;
1855 if (!baseType->isCanonicalUnqualified()) {
1856 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001857 canonSplit.Quals.addConsistentQualifiers(quals);
1858 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001859
1860 // Re-find the insert position.
1861 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1862 }
1863
1864 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1865 ExtQualNodes.InsertNode(eq, insertPos);
1866 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001867}
1868
Jay Foad4ba2a172011-01-12 09:06:06 +00001869QualType
1870ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001871 QualType CanT = getCanonicalType(T);
1872 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001873 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001874
John McCall0953e762009-09-24 19:53:00 +00001875 // If we are composing extended qualifiers together, merge together
1876 // into one ExtQuals node.
1877 QualifierCollector Quals;
1878 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001879
John McCall0953e762009-09-24 19:53:00 +00001880 // If this type already has an address space specified, it cannot get
1881 // another one.
1882 assert(!Quals.hasAddressSpace() &&
1883 "Type cannot be in multiple addr spaces!");
1884 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001885
John McCall0953e762009-09-24 19:53:00 +00001886 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001887}
1888
Chris Lattnerb7d25532009-02-18 22:53:11 +00001889QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001890 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001891 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001892 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001893 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001894
John McCall7f040a92010-12-24 02:08:15 +00001895 if (const PointerType *ptr = T->getAs<PointerType>()) {
1896 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001897 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001898 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1899 return getPointerType(ResultType);
1900 }
1901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
John McCall0953e762009-09-24 19:53:00 +00001903 // If we are composing extended qualifiers together, merge together
1904 // into one ExtQuals node.
1905 QualifierCollector Quals;
1906 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001907
John McCall0953e762009-09-24 19:53:00 +00001908 // If this type already has an ObjCGC specified, it cannot get
1909 // another one.
1910 assert(!Quals.hasObjCGCAttr() &&
1911 "Type cannot have multiple ObjCGCs!");
1912 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001913
John McCall0953e762009-09-24 19:53:00 +00001914 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001915}
Chris Lattnera7674d82007-07-13 22:13:22 +00001916
John McCalle6a365d2010-12-19 02:44:49 +00001917const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1918 FunctionType::ExtInfo Info) {
1919 if (T->getExtInfo() == Info)
1920 return T;
1921
1922 QualType Result;
1923 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1924 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1925 } else {
1926 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1927 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1928 EPI.ExtInfo = Info;
1929 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1930 FPT->getNumArgs(), EPI);
1931 }
1932
1933 return cast<FunctionType>(Result.getTypePtr());
1934}
1935
Reid Spencer5f016e22007-07-11 17:01:13 +00001936/// getComplexType - Return the uniqued reference to the type for a complex
1937/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001938QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 // Unique pointers, to guarantee there is only one pointer of a particular
1940 // structure.
1941 llvm::FoldingSetNodeID ID;
1942 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 void *InsertPos = 0;
1945 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1946 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 // If the pointee type isn't canonical, this won't be a canonical type either,
1949 // so fill in the canonical type field.
1950 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001951 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001952 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 // Get the new insert position for the node we care about.
1955 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001956 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 }
John McCall6b304a02009-09-24 23:30:46 +00001958 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 Types.push_back(New);
1960 ComplexTypes.InsertNode(New, InsertPos);
1961 return QualType(New, 0);
1962}
1963
Reid Spencer5f016e22007-07-11 17:01:13 +00001964/// getPointerType - Return the uniqued reference to the type for a pointer to
1965/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001966QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 // Unique pointers, to guarantee there is only one pointer of a particular
1968 // structure.
1969 llvm::FoldingSetNodeID ID;
1970 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 void *InsertPos = 0;
1973 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1974 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 // If the pointee type isn't canonical, this won't be a canonical type either,
1977 // so fill in the canonical type field.
1978 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001979 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001980 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 // Get the new insert position for the node we care about.
1983 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001984 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 }
John McCall6b304a02009-09-24 23:30:46 +00001986 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 Types.push_back(New);
1988 PointerTypes.InsertNode(New, InsertPos);
1989 return QualType(New, 0);
1990}
1991
Mike Stump1eb44332009-09-09 15:08:12 +00001992/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001993/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001994QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001995 assert(T->isFunctionType() && "block of function types only");
1996 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001997 // structure.
1998 llvm::FoldingSetNodeID ID;
1999 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Steve Naroff5618bd42008-08-27 16:04:49 +00002001 void *InsertPos = 0;
2002 if (BlockPointerType *PT =
2003 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2004 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002005
2006 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002007 // type either so fill in the canonical type field.
2008 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002009 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002010 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Steve Naroff5618bd42008-08-27 16:04:49 +00002012 // Get the new insert position for the node we care about.
2013 BlockPointerType *NewIP =
2014 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002015 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002016 }
John McCall6b304a02009-09-24 23:30:46 +00002017 BlockPointerType *New
2018 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002019 Types.push_back(New);
2020 BlockPointerTypes.InsertNode(New, InsertPos);
2021 return QualType(New, 0);
2022}
2023
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002024/// getLValueReferenceType - Return the uniqued reference to the type for an
2025/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002026QualType
2027ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002028 assert(getCanonicalType(T) != OverloadTy &&
2029 "Unresolved overloaded function type");
2030
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 // Unique pointers, to guarantee there is only one pointer of a particular
2032 // structure.
2033 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002034 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002035
2036 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002037 if (LValueReferenceType *RT =
2038 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002040
John McCall54e14c42009-10-22 22:37:11 +00002041 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2042
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 // If the referencee type isn't canonical, this won't be a canonical type
2044 // either, so fill in the canonical type field.
2045 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002046 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2047 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2048 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002049
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002051 LValueReferenceType *NewIP =
2052 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002053 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 }
2055
John McCall6b304a02009-09-24 23:30:46 +00002056 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002057 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2058 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002060 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002061
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002062 return QualType(New, 0);
2063}
2064
2065/// getRValueReferenceType - Return the uniqued reference to the type for an
2066/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002067QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002068 // Unique pointers, to guarantee there is only one pointer of a particular
2069 // structure.
2070 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002071 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002072
2073 void *InsertPos = 0;
2074 if (RValueReferenceType *RT =
2075 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2076 return QualType(RT, 0);
2077
John McCall54e14c42009-10-22 22:37:11 +00002078 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2079
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002080 // If the referencee type isn't canonical, this won't be a canonical type
2081 // either, so fill in the canonical type field.
2082 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002083 if (InnerRef || !T.isCanonical()) {
2084 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2085 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002086
2087 // Get the new insert position for the node we care about.
2088 RValueReferenceType *NewIP =
2089 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002090 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002091 }
2092
John McCall6b304a02009-09-24 23:30:46 +00002093 RValueReferenceType *New
2094 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002095 Types.push_back(New);
2096 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 return QualType(New, 0);
2098}
2099
Sebastian Redlf30208a2009-01-24 21:16:55 +00002100/// getMemberPointerType - Return the uniqued reference to the type for a
2101/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002102QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002103 // Unique pointers, to guarantee there is only one pointer of a particular
2104 // structure.
2105 llvm::FoldingSetNodeID ID;
2106 MemberPointerType::Profile(ID, T, Cls);
2107
2108 void *InsertPos = 0;
2109 if (MemberPointerType *PT =
2110 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2111 return QualType(PT, 0);
2112
2113 // If the pointee or class type isn't canonical, this won't be a canonical
2114 // type either, so fill in the canonical type field.
2115 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002116 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002117 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2118
2119 // Get the new insert position for the node we care about.
2120 MemberPointerType *NewIP =
2121 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002122 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002123 }
John McCall6b304a02009-09-24 23:30:46 +00002124 MemberPointerType *New
2125 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002126 Types.push_back(New);
2127 MemberPointerTypes.InsertNode(New, InsertPos);
2128 return QualType(New, 0);
2129}
2130
Mike Stump1eb44332009-09-09 15:08:12 +00002131/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002132/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002133QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002134 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002135 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002136 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002137 assert((EltTy->isDependentType() ||
2138 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002139 "Constant array of VLAs is illegal!");
2140
Chris Lattner38aeec72009-05-13 04:12:56 +00002141 // Convert the array size into a canonical width matching the pointer size for
2142 // the target.
2143 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002144 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002145 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002148 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002151 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002152 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002154
John McCall3b657512011-01-19 10:06:00 +00002155 // If the element type isn't canonical or has qualifiers, this won't
2156 // be a canonical type either, so fill in the canonical type field.
2157 QualType Canon;
2158 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2159 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002160 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002161 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002162 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002163
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002165 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002166 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002167 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 }
Mike Stump1eb44332009-09-09 15:08:12 +00002169
John McCall6b304a02009-09-24 23:30:46 +00002170 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002171 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002172 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 Types.push_back(New);
2174 return QualType(New, 0);
2175}
2176
John McCallce889032011-01-18 08:40:38 +00002177/// getVariableArrayDecayedType - Turns the given type, which may be
2178/// variably-modified, into the corresponding type with all the known
2179/// sizes replaced with [*].
2180QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2181 // Vastly most common case.
2182 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002183
John McCallce889032011-01-18 08:40:38 +00002184 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002185
John McCallce889032011-01-18 08:40:38 +00002186 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002187 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002188 switch (ty->getTypeClass()) {
2189#define TYPE(Class, Base)
2190#define ABSTRACT_TYPE(Class, Base)
2191#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2192#include "clang/AST/TypeNodes.def"
2193 llvm_unreachable("didn't desugar past all non-canonical types?");
2194
2195 // These types should never be variably-modified.
2196 case Type::Builtin:
2197 case Type::Complex:
2198 case Type::Vector:
2199 case Type::ExtVector:
2200 case Type::DependentSizedExtVector:
2201 case Type::ObjCObject:
2202 case Type::ObjCInterface:
2203 case Type::ObjCObjectPointer:
2204 case Type::Record:
2205 case Type::Enum:
2206 case Type::UnresolvedUsing:
2207 case Type::TypeOfExpr:
2208 case Type::TypeOf:
2209 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002210 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002211 case Type::DependentName:
2212 case Type::InjectedClassName:
2213 case Type::TemplateSpecialization:
2214 case Type::DependentTemplateSpecialization:
2215 case Type::TemplateTypeParm:
2216 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002217 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002218 case Type::PackExpansion:
2219 llvm_unreachable("type should never be variably-modified");
2220
2221 // These types can be variably-modified but should never need to
2222 // further decay.
2223 case Type::FunctionNoProto:
2224 case Type::FunctionProto:
2225 case Type::BlockPointer:
2226 case Type::MemberPointer:
2227 return type;
2228
2229 // These types can be variably-modified. All these modifications
2230 // preserve structure except as noted by comments.
2231 // TODO: if we ever care about optimizing VLAs, there are no-op
2232 // optimizations available here.
2233 case Type::Pointer:
2234 result = getPointerType(getVariableArrayDecayedType(
2235 cast<PointerType>(ty)->getPointeeType()));
2236 break;
2237
2238 case Type::LValueReference: {
2239 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2240 result = getLValueReferenceType(
2241 getVariableArrayDecayedType(lv->getPointeeType()),
2242 lv->isSpelledAsLValue());
2243 break;
2244 }
2245
2246 case Type::RValueReference: {
2247 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2248 result = getRValueReferenceType(
2249 getVariableArrayDecayedType(lv->getPointeeType()));
2250 break;
2251 }
2252
Eli Friedmanb001de72011-10-06 23:00:33 +00002253 case Type::Atomic: {
2254 const AtomicType *at = cast<AtomicType>(ty);
2255 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2256 break;
2257 }
2258
John McCallce889032011-01-18 08:40:38 +00002259 case Type::ConstantArray: {
2260 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2261 result = getConstantArrayType(
2262 getVariableArrayDecayedType(cat->getElementType()),
2263 cat->getSize(),
2264 cat->getSizeModifier(),
2265 cat->getIndexTypeCVRQualifiers());
2266 break;
2267 }
2268
2269 case Type::DependentSizedArray: {
2270 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2271 result = getDependentSizedArrayType(
2272 getVariableArrayDecayedType(dat->getElementType()),
2273 dat->getSizeExpr(),
2274 dat->getSizeModifier(),
2275 dat->getIndexTypeCVRQualifiers(),
2276 dat->getBracketsRange());
2277 break;
2278 }
2279
2280 // Turn incomplete types into [*] types.
2281 case Type::IncompleteArray: {
2282 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2283 result = getVariableArrayType(
2284 getVariableArrayDecayedType(iat->getElementType()),
2285 /*size*/ 0,
2286 ArrayType::Normal,
2287 iat->getIndexTypeCVRQualifiers(),
2288 SourceRange());
2289 break;
2290 }
2291
2292 // Turn VLA types into [*] types.
2293 case Type::VariableArray: {
2294 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2295 result = getVariableArrayType(
2296 getVariableArrayDecayedType(vat->getElementType()),
2297 /*size*/ 0,
2298 ArrayType::Star,
2299 vat->getIndexTypeCVRQualifiers(),
2300 vat->getBracketsRange());
2301 break;
2302 }
2303 }
2304
2305 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002306 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002307}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002308
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002309/// getVariableArrayType - Returns a non-unique reference to the type for a
2310/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002311QualType ASTContext::getVariableArrayType(QualType EltTy,
2312 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002313 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002314 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002315 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002316 // Since we don't unique expressions, it isn't possible to unique VLA's
2317 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002318 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002319
John McCall3b657512011-01-19 10:06:00 +00002320 // Be sure to pull qualifiers off the element type.
2321 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2322 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002323 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002324 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002325 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002326 }
2327
John McCall6b304a02009-09-24 23:30:46 +00002328 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002329 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002330
2331 VariableArrayTypes.push_back(New);
2332 Types.push_back(New);
2333 return QualType(New, 0);
2334}
2335
Douglas Gregor898574e2008-12-05 23:32:09 +00002336/// getDependentSizedArrayType - Returns a non-unique reference to
2337/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002338/// type.
John McCall3b657512011-01-19 10:06:00 +00002339QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2340 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002341 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002342 unsigned elementTypeQuals,
2343 SourceRange brackets) const {
2344 assert((!numElements || numElements->isTypeDependent() ||
2345 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002346 "Size must be type- or value-dependent!");
2347
John McCall3b657512011-01-19 10:06:00 +00002348 // Dependently-sized array types that do not have a specified number
2349 // of elements will have their sizes deduced from a dependent
2350 // initializer. We do no canonicalization here at all, which is okay
2351 // because they can't be used in most locations.
2352 if (!numElements) {
2353 DependentSizedArrayType *newType
2354 = new (*this, TypeAlignment)
2355 DependentSizedArrayType(*this, elementType, QualType(),
2356 numElements, ASM, elementTypeQuals,
2357 brackets);
2358 Types.push_back(newType);
2359 return QualType(newType, 0);
2360 }
2361
2362 // Otherwise, we actually build a new type every time, but we
2363 // also build a canonical type.
2364
2365 SplitQualType canonElementType = getCanonicalType(elementType).split();
2366
2367 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002368 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002369 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002370 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002371 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002372
John McCall3b657512011-01-19 10:06:00 +00002373 // Look for an existing type with these properties.
2374 DependentSizedArrayType *canonTy =
2375 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002376
John McCall3b657512011-01-19 10:06:00 +00002377 // If we don't have one, build one.
2378 if (!canonTy) {
2379 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002380 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002381 QualType(), numElements, ASM, elementTypeQuals,
2382 brackets);
2383 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2384 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002385 }
2386
John McCall3b657512011-01-19 10:06:00 +00002387 // Apply qualifiers from the element type to the array.
2388 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002389 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002390
John McCall3b657512011-01-19 10:06:00 +00002391 // If we didn't need extra canonicalization for the element type,
2392 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002393 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002394 return canon;
2395
2396 // Otherwise, we need to build a type which follows the spelling
2397 // of the element type.
2398 DependentSizedArrayType *sugaredType
2399 = new (*this, TypeAlignment)
2400 DependentSizedArrayType(*this, elementType, canon, numElements,
2401 ASM, elementTypeQuals, brackets);
2402 Types.push_back(sugaredType);
2403 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002404}
2405
John McCall3b657512011-01-19 10:06:00 +00002406QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002407 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002408 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002409 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002410 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002411
John McCall3b657512011-01-19 10:06:00 +00002412 void *insertPos = 0;
2413 if (IncompleteArrayType *iat =
2414 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2415 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002416
2417 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002418 // either, so fill in the canonical type field. We also have to pull
2419 // qualifiers off the element type.
2420 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002421
John McCall3b657512011-01-19 10:06:00 +00002422 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2423 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002424 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002425 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002426 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002427
2428 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002429 IncompleteArrayType *existing =
2430 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2431 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002432 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002433
John McCall3b657512011-01-19 10:06:00 +00002434 IncompleteArrayType *newType = new (*this, TypeAlignment)
2435 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002436
John McCall3b657512011-01-19 10:06:00 +00002437 IncompleteArrayTypes.InsertNode(newType, insertPos);
2438 Types.push_back(newType);
2439 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002440}
2441
Steve Naroff73322922007-07-18 18:00:27 +00002442/// getVectorType - Return the unique reference to a vector type of
2443/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002444QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002445 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002446 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Reid Spencer5f016e22007-07-11 17:01:13 +00002448 // Check if we've already instantiated a vector of this type.
2449 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002450 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002451
Reid Spencer5f016e22007-07-11 17:01:13 +00002452 void *InsertPos = 0;
2453 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2454 return QualType(VTP, 0);
2455
2456 // If the element type isn't canonical, this won't be a canonical type either,
2457 // so fill in the canonical type field.
2458 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002459 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002460 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Reid Spencer5f016e22007-07-11 17:01:13 +00002462 // Get the new insert position for the node we care about.
2463 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002464 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002465 }
John McCall6b304a02009-09-24 23:30:46 +00002466 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002467 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 VectorTypes.InsertNode(New, InsertPos);
2469 Types.push_back(New);
2470 return QualType(New, 0);
2471}
2472
Nate Begeman213541a2008-04-18 23:10:10 +00002473/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002474/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002475QualType
2476ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002477 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Steve Naroff73322922007-07-18 18:00:27 +00002479 // Check if we've already instantiated a vector of this type.
2480 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002481 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002482 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002483 void *InsertPos = 0;
2484 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2485 return QualType(VTP, 0);
2486
2487 // If the element type isn't canonical, this won't be a canonical type either,
2488 // so fill in the canonical type field.
2489 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002490 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002491 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002492
Steve Naroff73322922007-07-18 18:00:27 +00002493 // Get the new insert position for the node we care about.
2494 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002495 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002496 }
John McCall6b304a02009-09-24 23:30:46 +00002497 ExtVectorType *New = new (*this, TypeAlignment)
2498 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002499 VectorTypes.InsertNode(New, InsertPos);
2500 Types.push_back(New);
2501 return QualType(New, 0);
2502}
2503
Jay Foad4ba2a172011-01-12 09:06:06 +00002504QualType
2505ASTContext::getDependentSizedExtVectorType(QualType vecType,
2506 Expr *SizeExpr,
2507 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002508 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002509 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002510 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002512 void *InsertPos = 0;
2513 DependentSizedExtVectorType *Canon
2514 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2515 DependentSizedExtVectorType *New;
2516 if (Canon) {
2517 // We already have a canonical version of this array type; use it as
2518 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002519 New = new (*this, TypeAlignment)
2520 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2521 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002522 } else {
2523 QualType CanonVecTy = getCanonicalType(vecType);
2524 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002525 New = new (*this, TypeAlignment)
2526 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2527 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002528
2529 DependentSizedExtVectorType *CanonCheck
2530 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2531 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2532 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002533 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2534 } else {
2535 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2536 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002537 New = new (*this, TypeAlignment)
2538 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002539 }
2540 }
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002542 Types.push_back(New);
2543 return QualType(New, 0);
2544}
2545
Douglas Gregor72564e72009-02-26 23:50:07 +00002546/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002547///
Jay Foad4ba2a172011-01-12 09:06:06 +00002548QualType
2549ASTContext::getFunctionNoProtoType(QualType ResultTy,
2550 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002551 const CallingConv DefaultCC = Info.getCC();
2552 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2553 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 // Unique functions, to guarantee there is only one function of a particular
2555 // structure.
2556 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002557 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002560 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002561 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002563
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002565 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002566 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002567 Canonical =
2568 getFunctionNoProtoType(getCanonicalType(ResultTy),
2569 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002570
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002572 FunctionNoProtoType *NewIP =
2573 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002574 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 }
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Roman Divackycfe9af22011-03-01 17:40:53 +00002577 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002578 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002579 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002580 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002581 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 return QualType(New, 0);
2583}
2584
2585/// getFunctionType - Return a normal function type with a typed argument
2586/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002587QualType
2588ASTContext::getFunctionType(QualType ResultTy,
2589 const QualType *ArgArray, unsigned NumArgs,
2590 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 // Unique functions, to guarantee there is only one function of a particular
2592 // structure.
2593 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002594 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002595
2596 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002597 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002598 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002599 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002600
2601 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002602 bool isCanonical =
2603 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2604 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002606 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002607 isCanonical = false;
2608
Roman Divackycfe9af22011-03-01 17:40:53 +00002609 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2610 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2611 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002612
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002614 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002616 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002617 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 CanonicalArgs.reserve(NumArgs);
2619 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002620 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002621
John McCalle23cf432010-12-14 08:05:40 +00002622 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002623 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002624 CanonicalEPI.ExceptionSpecType = EST_None;
2625 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002626 CanonicalEPI.ExtInfo
2627 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2628
Chris Lattnerf52ab252008-04-06 22:59:24 +00002629 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002630 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002631 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002632
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002634 FunctionProtoType *NewIP =
2635 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002636 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002638
John McCallf85e1932011-06-15 23:02:42 +00002639 // FunctionProtoType objects are allocated with extra bytes after
2640 // them for three variable size arrays at the end:
2641 // - parameter types
2642 // - exception types
2643 // - consumed-arguments flags
2644 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002645 // expression, or information used to resolve the exception
2646 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002647 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002648 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002649 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002650 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002651 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002652 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002653 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002654 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002655 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2656 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002657 }
John McCallf85e1932011-06-15 23:02:42 +00002658 if (EPI.ConsumedArguments)
2659 Size += NumArgs * sizeof(bool);
2660
John McCalle23cf432010-12-14 08:05:40 +00002661 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002662 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2663 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002664 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002666 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 return QualType(FTP, 0);
2668}
2669
John McCall3cb0ebd2010-03-10 03:28:59 +00002670#ifndef NDEBUG
2671static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2672 if (!isa<CXXRecordDecl>(D)) return false;
2673 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2674 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2675 return true;
2676 if (RD->getDescribedClassTemplate() &&
2677 !isa<ClassTemplateSpecializationDecl>(RD))
2678 return true;
2679 return false;
2680}
2681#endif
2682
2683/// getInjectedClassNameType - Return the unique reference to the
2684/// injected class name type for the specified templated declaration.
2685QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002686 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002687 assert(NeedsInjectedClassNameType(Decl));
2688 if (Decl->TypeForDecl) {
2689 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002690 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002691 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2692 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2693 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2694 } else {
John McCallf4c73712011-01-19 06:33:43 +00002695 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002696 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002697 Decl->TypeForDecl = newType;
2698 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002699 }
2700 return QualType(Decl->TypeForDecl, 0);
2701}
2702
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002703/// getTypeDeclType - Return the unique reference to the type for the
2704/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002705QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002706 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002707 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002708
Richard Smith162e1c12011-04-15 14:24:37 +00002709 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002710 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002711
John McCallbecb8d52010-03-10 06:48:02 +00002712 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2713 "Template type parameter types are always available.");
2714
John McCall19c85762010-02-16 03:57:14 +00002715 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002716 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002717 "struct/union has previous declaration");
2718 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002719 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002720 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002721 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002722 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002723 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002724 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002725 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002726 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2727 Decl->TypeForDecl = newType;
2728 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002729 } else
John McCallbecb8d52010-03-10 06:48:02 +00002730 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002731
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002732 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002733}
2734
Reid Spencer5f016e22007-07-11 17:01:13 +00002735/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002736/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002737QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002738ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2739 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002740 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002742 if (Canonical.isNull())
2743 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002744 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002745 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002746 Decl->TypeForDecl = newType;
2747 Types.push_back(newType);
2748 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002749}
2750
Jay Foad4ba2a172011-01-12 09:06:06 +00002751QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002752 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2753
Douglas Gregoref96ee02012-01-14 16:38:05 +00002754 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002755 if (PrevDecl->TypeForDecl)
2756 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2757
John McCallf4c73712011-01-19 06:33:43 +00002758 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2759 Decl->TypeForDecl = newType;
2760 Types.push_back(newType);
2761 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002762}
2763
Jay Foad4ba2a172011-01-12 09:06:06 +00002764QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002765 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2766
Douglas Gregoref96ee02012-01-14 16:38:05 +00002767 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002768 if (PrevDecl->TypeForDecl)
2769 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2770
John McCallf4c73712011-01-19 06:33:43 +00002771 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2772 Decl->TypeForDecl = newType;
2773 Types.push_back(newType);
2774 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002775}
2776
John McCall9d156a72011-01-06 01:58:22 +00002777QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2778 QualType modifiedType,
2779 QualType equivalentType) {
2780 llvm::FoldingSetNodeID id;
2781 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2782
2783 void *insertPos = 0;
2784 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2785 if (type) return QualType(type, 0);
2786
2787 QualType canon = getCanonicalType(equivalentType);
2788 type = new (*this, TypeAlignment)
2789 AttributedType(canon, attrKind, modifiedType, equivalentType);
2790
2791 Types.push_back(type);
2792 AttributedTypes.InsertNode(type, insertPos);
2793
2794 return QualType(type, 0);
2795}
2796
2797
John McCall49a832b2009-10-18 09:09:24 +00002798/// \brief Retrieve a substitution-result type.
2799QualType
2800ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002801 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002802 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002803 && "replacement types must always be canonical");
2804
2805 llvm::FoldingSetNodeID ID;
2806 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2807 void *InsertPos = 0;
2808 SubstTemplateTypeParmType *SubstParm
2809 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2810
2811 if (!SubstParm) {
2812 SubstParm = new (*this, TypeAlignment)
2813 SubstTemplateTypeParmType(Parm, Replacement);
2814 Types.push_back(SubstParm);
2815 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2816 }
2817
2818 return QualType(SubstParm, 0);
2819}
2820
Douglas Gregorc3069d62011-01-14 02:55:32 +00002821/// \brief Retrieve a
2822QualType ASTContext::getSubstTemplateTypeParmPackType(
2823 const TemplateTypeParmType *Parm,
2824 const TemplateArgument &ArgPack) {
2825#ifndef NDEBUG
2826 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2827 PEnd = ArgPack.pack_end();
2828 P != PEnd; ++P) {
2829 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2830 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2831 }
2832#endif
2833
2834 llvm::FoldingSetNodeID ID;
2835 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2836 void *InsertPos = 0;
2837 if (SubstTemplateTypeParmPackType *SubstParm
2838 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2839 return QualType(SubstParm, 0);
2840
2841 QualType Canon;
2842 if (!Parm->isCanonicalUnqualified()) {
2843 Canon = getCanonicalType(QualType(Parm, 0));
2844 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2845 ArgPack);
2846 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2847 }
2848
2849 SubstTemplateTypeParmPackType *SubstParm
2850 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2851 ArgPack);
2852 Types.push_back(SubstParm);
2853 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2854 return QualType(SubstParm, 0);
2855}
2856
Douglas Gregorfab9d672009-02-05 23:33:38 +00002857/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002858/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002859/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002860QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002861 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002862 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002863 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002864 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002865 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002866 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002867 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2868
2869 if (TypeParm)
2870 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002871
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002872 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002873 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002874 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002875
2876 TemplateTypeParmType *TypeCheck
2877 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2878 assert(!TypeCheck && "Template type parameter canonical type broken");
2879 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002880 } else
John McCall6b304a02009-09-24 23:30:46 +00002881 TypeParm = new (*this, TypeAlignment)
2882 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002883
2884 Types.push_back(TypeParm);
2885 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2886
2887 return QualType(TypeParm, 0);
2888}
2889
John McCall3cb0ebd2010-03-10 03:28:59 +00002890TypeSourceInfo *
2891ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2892 SourceLocation NameLoc,
2893 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002894 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002895 assert(!Name.getAsDependentTemplateName() &&
2896 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002897 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002898
2899 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2900 TemplateSpecializationTypeLoc TL
2901 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002902 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002903 TL.setTemplateNameLoc(NameLoc);
2904 TL.setLAngleLoc(Args.getLAngleLoc());
2905 TL.setRAngleLoc(Args.getRAngleLoc());
2906 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2907 TL.setArgLocInfo(i, Args[i].getLocInfo());
2908 return DI;
2909}
2910
Mike Stump1eb44332009-09-09 15:08:12 +00002911QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002912ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002913 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002914 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002915 assert(!Template.getAsDependentTemplateName() &&
2916 "No dependent template names here!");
2917
John McCalld5532b62009-11-23 01:53:49 +00002918 unsigned NumArgs = Args.size();
2919
Chris Lattner5f9e2722011-07-23 10:55:15 +00002920 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002921 ArgVec.reserve(NumArgs);
2922 for (unsigned i = 0; i != NumArgs; ++i)
2923 ArgVec.push_back(Args[i].getArgument());
2924
John McCall31f17ec2010-04-27 00:57:59 +00002925 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002926 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002927}
2928
Douglas Gregorb70126a2012-02-03 17:16:23 +00002929#ifndef NDEBUG
2930static bool hasAnyPackExpansions(const TemplateArgument *Args,
2931 unsigned NumArgs) {
2932 for (unsigned I = 0; I != NumArgs; ++I)
2933 if (Args[I].isPackExpansion())
2934 return true;
2935
2936 return true;
2937}
2938#endif
2939
John McCall833ca992009-10-29 08:12:44 +00002940QualType
2941ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002942 const TemplateArgument *Args,
2943 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002944 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002945 assert(!Template.getAsDependentTemplateName() &&
2946 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002947 // Look through qualified template names.
2948 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2949 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002950
Douglas Gregorb70126a2012-02-03 17:16:23 +00002951 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002952 Template.getAsTemplateDecl() &&
2953 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002954 QualType CanonType;
2955 if (!Underlying.isNull())
2956 CanonType = getCanonicalType(Underlying);
2957 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002958 // We can get here with an alias template when the specialization contains
2959 // a pack expansion that does not match up with a parameter pack.
2960 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2961 "Caller must compute aliased type");
2962 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002963 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2964 NumArgs);
2965 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002966
Douglas Gregor1275ae02009-07-28 23:00:59 +00002967 // Allocate the (non-canonical) template specialization type, but don't
2968 // try to unique it: these types typically have location information that
2969 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002970 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2971 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002972 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002973 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002974 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002975 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2976 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Douglas Gregor55f6b142009-02-09 18:46:07 +00002978 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002979 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002980}
2981
Mike Stump1eb44332009-09-09 15:08:12 +00002982QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002983ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2984 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002985 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002986 assert(!Template.getAsDependentTemplateName() &&
2987 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002988
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002989 // Look through qualified template names.
2990 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2991 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002992
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002993 // Build the canonical template specialization type.
2994 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002995 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002996 CanonArgs.reserve(NumArgs);
2997 for (unsigned I = 0; I != NumArgs; ++I)
2998 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2999
3000 // Determine whether this canonical template specialization type already
3001 // exists.
3002 llvm::FoldingSetNodeID ID;
3003 TemplateSpecializationType::Profile(ID, CanonTemplate,
3004 CanonArgs.data(), NumArgs, *this);
3005
3006 void *InsertPos = 0;
3007 TemplateSpecializationType *Spec
3008 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3009
3010 if (!Spec) {
3011 // Allocate a new canonical template specialization type.
3012 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3013 sizeof(TemplateArgument) * NumArgs),
3014 TypeAlignment);
3015 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3016 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003017 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003018 Types.push_back(Spec);
3019 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3020 }
3021
3022 assert(Spec->isDependentType() &&
3023 "Non-dependent template-id type must have a canonical type");
3024 return QualType(Spec, 0);
3025}
3026
3027QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003028ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3029 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003030 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003031 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003032 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003033
3034 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003035 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003036 if (T)
3037 return QualType(T, 0);
3038
Douglas Gregor789b1f62010-02-04 18:10:26 +00003039 QualType Canon = NamedType;
3040 if (!Canon.isCanonical()) {
3041 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003042 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3043 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003044 (void)CheckT;
3045 }
3046
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003047 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003048 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003049 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003050 return QualType(T, 0);
3051}
3052
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003053QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003054ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003055 llvm::FoldingSetNodeID ID;
3056 ParenType::Profile(ID, InnerType);
3057
3058 void *InsertPos = 0;
3059 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3060 if (T)
3061 return QualType(T, 0);
3062
3063 QualType Canon = InnerType;
3064 if (!Canon.isCanonical()) {
3065 Canon = getCanonicalType(InnerType);
3066 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3067 assert(!CheckT && "Paren canonical type broken");
3068 (void)CheckT;
3069 }
3070
3071 T = new (*this) ParenType(InnerType, Canon);
3072 Types.push_back(T);
3073 ParenTypes.InsertNode(T, InsertPos);
3074 return QualType(T, 0);
3075}
3076
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003077QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3078 NestedNameSpecifier *NNS,
3079 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003080 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003081 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3082
3083 if (Canon.isNull()) {
3084 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003085 ElaboratedTypeKeyword CanonKeyword = Keyword;
3086 if (Keyword == ETK_None)
3087 CanonKeyword = ETK_Typename;
3088
3089 if (CanonNNS != NNS || CanonKeyword != Keyword)
3090 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003091 }
3092
3093 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003094 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003095
3096 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003097 DependentNameType *T
3098 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003099 if (T)
3100 return QualType(T, 0);
3101
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003102 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003103 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003104 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003105 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003106}
3107
Mike Stump1eb44332009-09-09 15:08:12 +00003108QualType
John McCall33500952010-06-11 00:33:02 +00003109ASTContext::getDependentTemplateSpecializationType(
3110 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003111 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003112 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003113 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003114 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003115 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003116 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3117 ArgCopy.push_back(Args[I].getArgument());
3118 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3119 ArgCopy.size(),
3120 ArgCopy.data());
3121}
3122
3123QualType
3124ASTContext::getDependentTemplateSpecializationType(
3125 ElaboratedTypeKeyword Keyword,
3126 NestedNameSpecifier *NNS,
3127 const IdentifierInfo *Name,
3128 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003129 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003130 assert((!NNS || NNS->isDependent()) &&
3131 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003132
Douglas Gregor789b1f62010-02-04 18:10:26 +00003133 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003134 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3135 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003136
3137 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003138 DependentTemplateSpecializationType *T
3139 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003140 if (T)
3141 return QualType(T, 0);
3142
John McCall33500952010-06-11 00:33:02 +00003143 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003144
John McCall33500952010-06-11 00:33:02 +00003145 ElaboratedTypeKeyword CanonKeyword = Keyword;
3146 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3147
3148 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003149 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003150 for (unsigned I = 0; I != NumArgs; ++I) {
3151 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3152 if (!CanonArgs[I].structurallyEquals(Args[I]))
3153 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003154 }
3155
John McCall33500952010-06-11 00:33:02 +00003156 QualType Canon;
3157 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3158 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3159 Name, NumArgs,
3160 CanonArgs.data());
3161
3162 // Find the insert position again.
3163 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3164 }
3165
3166 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3167 sizeof(TemplateArgument) * NumArgs),
3168 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003169 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003170 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003171 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003172 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003173 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003174}
3175
Douglas Gregorcded4f62011-01-14 17:04:44 +00003176QualType ASTContext::getPackExpansionType(QualType Pattern,
3177 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003178 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003179 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003180
3181 assert(Pattern->containsUnexpandedParameterPack() &&
3182 "Pack expansions must expand one or more parameter packs");
3183 void *InsertPos = 0;
3184 PackExpansionType *T
3185 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3186 if (T)
3187 return QualType(T, 0);
3188
3189 QualType Canon;
3190 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003191 Canon = getCanonicalType(Pattern);
3192 // The canonical type might not contain an unexpanded parameter pack, if it
3193 // contains an alias template specialization which ignores one of its
3194 // parameters.
3195 if (Canon->containsUnexpandedParameterPack()) {
3196 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003197
Richard Smithd8672ef2012-07-16 00:20:35 +00003198 // Find the insert position again, in case we inserted an element into
3199 // PackExpansionTypes and invalidated our insert position.
3200 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3201 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003202 }
3203
Douglas Gregorcded4f62011-01-14 17:04:44 +00003204 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003205 Types.push_back(T);
3206 PackExpansionTypes.InsertNode(T, InsertPos);
3207 return QualType(T, 0);
3208}
3209
Chris Lattner88cb27a2008-04-07 04:56:42 +00003210/// CmpProtocolNames - Comparison predicate for sorting protocols
3211/// alphabetically.
3212static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3213 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003214 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003215}
3216
John McCallc12c5bb2010-05-15 11:32:37 +00003217static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003218 unsigned NumProtocols) {
3219 if (NumProtocols == 0) return true;
3220
Douglas Gregor61cc2962012-01-02 02:00:30 +00003221 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3222 return false;
3223
John McCall54e14c42009-10-22 22:37:11 +00003224 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003225 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3226 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003227 return false;
3228 return true;
3229}
3230
3231static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003232 unsigned &NumProtocols) {
3233 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003234
Chris Lattner88cb27a2008-04-07 04:56:42 +00003235 // Sort protocols, keyed by name.
3236 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3237
Douglas Gregor61cc2962012-01-02 02:00:30 +00003238 // Canonicalize.
3239 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3240 Protocols[I] = Protocols[I]->getCanonicalDecl();
3241
Chris Lattner88cb27a2008-04-07 04:56:42 +00003242 // Remove duplicates.
3243 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3244 NumProtocols = ProtocolsEnd-Protocols;
3245}
3246
John McCallc12c5bb2010-05-15 11:32:37 +00003247QualType ASTContext::getObjCObjectType(QualType BaseType,
3248 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003249 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003250 // If the base type is an interface and there aren't any protocols
3251 // to add, then the interface type will do just fine.
3252 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3253 return BaseType;
3254
3255 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003256 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003257 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003258 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003259 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3260 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003261
John McCallc12c5bb2010-05-15 11:32:37 +00003262 // Build the canonical type, which has the canonical base type and
3263 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003264 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003265 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3266 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3267 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003268 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003269 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003270 unsigned UniqueCount = NumProtocols;
3271
John McCall54e14c42009-10-22 22:37:11 +00003272 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003273 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3274 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003275 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003276 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3277 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003278 }
3279
3280 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003281 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3282 }
3283
3284 unsigned Size = sizeof(ObjCObjectTypeImpl);
3285 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3286 void *Mem = Allocate(Size, TypeAlignment);
3287 ObjCObjectTypeImpl *T =
3288 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3289
3290 Types.push_back(T);
3291 ObjCObjectTypes.InsertNode(T, InsertPos);
3292 return QualType(T, 0);
3293}
3294
3295/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3296/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003297QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003298 llvm::FoldingSetNodeID ID;
3299 ObjCObjectPointerType::Profile(ID, ObjectT);
3300
3301 void *InsertPos = 0;
3302 if (ObjCObjectPointerType *QT =
3303 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3304 return QualType(QT, 0);
3305
3306 // Find the canonical object type.
3307 QualType Canonical;
3308 if (!ObjectT.isCanonical()) {
3309 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3310
3311 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003312 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3313 }
3314
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003315 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003316 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3317 ObjCObjectPointerType *QType =
3318 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003319
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003320 Types.push_back(QType);
3321 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003322 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003323}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003324
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003325/// getObjCInterfaceType - Return the unique reference to the type for the
3326/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003327QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3328 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003329 if (Decl->TypeForDecl)
3330 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Douglas Gregor0af55012011-12-16 03:12:41 +00003332 if (PrevDecl) {
3333 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3334 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3335 return QualType(PrevDecl->TypeForDecl, 0);
3336 }
3337
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003338 // Prefer the definition, if there is one.
3339 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3340 Decl = Def;
3341
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003342 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3343 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3344 Decl->TypeForDecl = T;
3345 Types.push_back(T);
3346 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003347}
3348
Douglas Gregor72564e72009-02-26 23:50:07 +00003349/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3350/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003351/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003352/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003353/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003354QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003355 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003356 if (tofExpr->isTypeDependent()) {
3357 llvm::FoldingSetNodeID ID;
3358 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Douglas Gregorb1975722009-07-30 23:18:24 +00003360 void *InsertPos = 0;
3361 DependentTypeOfExprType *Canon
3362 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3363 if (Canon) {
3364 // We already have a "canonical" version of an identical, dependent
3365 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003366 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003367 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003368 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003369 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003370 Canon
3371 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003372 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3373 toe = Canon;
3374 }
3375 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003376 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003377 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003378 }
Steve Naroff9752f252007-08-01 18:02:17 +00003379 Types.push_back(toe);
3380 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003381}
3382
Steve Naroff9752f252007-08-01 18:02:17 +00003383/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3384/// TypeOfType AST's. The only motivation to unique these nodes would be
3385/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003386/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003387/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003388QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003389 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003390 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003391 Types.push_back(tot);
3392 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003393}
3394
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003395
Anders Carlsson395b4752009-06-24 19:06:50 +00003396/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3397/// DecltypeType AST's. The only motivation to unique these nodes would be
3398/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003399/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003400/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003401QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003402 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003403
3404 // C++0x [temp.type]p2:
3405 // If an expression e involves a template parameter, decltype(e) denotes a
3406 // unique dependent type. Two such decltype-specifiers refer to the same
3407 // type only if their expressions are equivalent (14.5.6.1).
3408 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003409 llvm::FoldingSetNodeID ID;
3410 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003412 void *InsertPos = 0;
3413 DependentDecltypeType *Canon
3414 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3415 if (Canon) {
3416 // We already have a "canonical" version of an equivalent, dependent
3417 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003418 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003419 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003420 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003421 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003422 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003423 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3424 dt = Canon;
3425 }
3426 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003427 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3428 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003429 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003430 Types.push_back(dt);
3431 return QualType(dt, 0);
3432}
3433
Sean Huntca63c202011-05-24 22:41:36 +00003434/// getUnaryTransformationType - We don't unique these, since the memory
3435/// savings are minimal and these are rare.
3436QualType ASTContext::getUnaryTransformType(QualType BaseType,
3437 QualType UnderlyingType,
3438 UnaryTransformType::UTTKind Kind)
3439 const {
3440 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003441 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3442 Kind,
3443 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003444 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003445 Types.push_back(Ty);
3446 return QualType(Ty, 0);
3447}
3448
Richard Smith483b9f32011-02-21 20:05:19 +00003449/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003450QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003451 void *InsertPos = 0;
3452 if (!DeducedType.isNull()) {
3453 // Look in the folding set for an existing type.
3454 llvm::FoldingSetNodeID ID;
3455 AutoType::Profile(ID, DeducedType);
3456 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3457 return QualType(AT, 0);
3458 }
3459
3460 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3461 Types.push_back(AT);
3462 if (InsertPos)
3463 AutoTypes.InsertNode(AT, InsertPos);
3464 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003465}
3466
Eli Friedmanb001de72011-10-06 23:00:33 +00003467/// getAtomicType - Return the uniqued reference to the atomic type for
3468/// the given value type.
3469QualType ASTContext::getAtomicType(QualType T) const {
3470 // Unique pointers, to guarantee there is only one pointer of a particular
3471 // structure.
3472 llvm::FoldingSetNodeID ID;
3473 AtomicType::Profile(ID, T);
3474
3475 void *InsertPos = 0;
3476 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3477 return QualType(AT, 0);
3478
3479 // If the atomic value type isn't canonical, this won't be a canonical type
3480 // either, so fill in the canonical type field.
3481 QualType Canonical;
3482 if (!T.isCanonical()) {
3483 Canonical = getAtomicType(getCanonicalType(T));
3484
3485 // Get the new insert position for the node we care about.
3486 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3487 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3488 }
3489 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3490 Types.push_back(New);
3491 AtomicTypes.InsertNode(New, InsertPos);
3492 return QualType(New, 0);
3493}
3494
Richard Smithad762fc2011-04-14 22:09:26 +00003495/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3496QualType ASTContext::getAutoDeductType() const {
3497 if (AutoDeductTy.isNull())
3498 AutoDeductTy = getAutoType(QualType());
3499 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3500 return AutoDeductTy;
3501}
3502
3503/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3504QualType ASTContext::getAutoRRefDeductType() const {
3505 if (AutoRRefDeductTy.isNull())
3506 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3507 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3508 return AutoRRefDeductTy;
3509}
3510
Reid Spencer5f016e22007-07-11 17:01:13 +00003511/// getTagDeclType - Return the unique reference to the type for the
3512/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003513QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003514 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003515 // FIXME: What is the design on getTagDeclType when it requires casting
3516 // away const? mutable?
3517 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003518}
3519
Mike Stump1eb44332009-09-09 15:08:12 +00003520/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3521/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3522/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003523CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003524 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003525}
3526
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003527/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3528CanQualType ASTContext::getIntMaxType() const {
3529 return getFromTargetType(Target->getIntMaxType());
3530}
3531
3532/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3533CanQualType ASTContext::getUIntMaxType() const {
3534 return getFromTargetType(Target->getUIntMaxType());
3535}
3536
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003537/// getSignedWCharType - Return the type of "signed wchar_t".
3538/// Used when in C++, as a GCC extension.
3539QualType ASTContext::getSignedWCharType() const {
3540 // FIXME: derive from "Target" ?
3541 return WCharTy;
3542}
3543
3544/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3545/// Used when in C++, as a GCC extension.
3546QualType ASTContext::getUnsignedWCharType() const {
3547 // FIXME: derive from "Target" ?
3548 return UnsignedIntTy;
3549}
3550
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003551/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003552/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3553QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003554 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003555}
3556
Eli Friedman6902e412012-11-27 02:58:24 +00003557/// \brief Return the unique type for "pid_t" defined in
3558/// <sys/types.h>. We need this to compute the correct type for vfork().
3559QualType ASTContext::getProcessIDType() const {
3560 return getFromTargetType(Target->getProcessIDType());
3561}
3562
Chris Lattnere6327742008-04-02 05:18:44 +00003563//===----------------------------------------------------------------------===//
3564// Type Operators
3565//===----------------------------------------------------------------------===//
3566
Jay Foad4ba2a172011-01-12 09:06:06 +00003567CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003568 // Push qualifiers into arrays, and then discard any remaining
3569 // qualifiers.
3570 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003571 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003572 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003573 QualType Result;
3574 if (isa<ArrayType>(Ty)) {
3575 Result = getArrayDecayedType(QualType(Ty,0));
3576 } else if (isa<FunctionType>(Ty)) {
3577 Result = getPointerType(QualType(Ty, 0));
3578 } else {
3579 Result = QualType(Ty, 0);
3580 }
3581
3582 return CanQualType::CreateUnsafe(Result);
3583}
3584
John McCall62c28c82011-01-18 07:41:22 +00003585QualType ASTContext::getUnqualifiedArrayType(QualType type,
3586 Qualifiers &quals) {
3587 SplitQualType splitType = type.getSplitUnqualifiedType();
3588
3589 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3590 // the unqualified desugared type and then drops it on the floor.
3591 // We then have to strip that sugar back off with
3592 // getUnqualifiedDesugaredType(), which is silly.
3593 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003594 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003595
3596 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003597 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003598 quals = splitType.Quals;
3599 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003600 }
3601
John McCall62c28c82011-01-18 07:41:22 +00003602 // Otherwise, recurse on the array's element type.
3603 QualType elementType = AT->getElementType();
3604 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3605
3606 // If that didn't change the element type, AT has no qualifiers, so we
3607 // can just use the results in splitType.
3608 if (elementType == unqualElementType) {
3609 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003610 quals = splitType.Quals;
3611 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003612 }
3613
3614 // Otherwise, add in the qualifiers from the outermost type, then
3615 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003616 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003617
Douglas Gregor9dadd942010-05-17 18:45:21 +00003618 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003619 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003620 CAT->getSizeModifier(), 0);
3621 }
3622
Douglas Gregor9dadd942010-05-17 18:45:21 +00003623 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003624 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003625 }
3626
Douglas Gregor9dadd942010-05-17 18:45:21 +00003627 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003628 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003629 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003630 VAT->getSizeModifier(),
3631 VAT->getIndexTypeCVRQualifiers(),
3632 VAT->getBracketsRange());
3633 }
3634
3635 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003636 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003637 DSAT->getSizeModifier(), 0,
3638 SourceRange());
3639}
3640
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003641/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3642/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3643/// they point to and return true. If T1 and T2 aren't pointer types
3644/// or pointer-to-member types, or if they are not similar at this
3645/// level, returns false and leaves T1 and T2 unchanged. Top-level
3646/// qualifiers on T1 and T2 are ignored. This function will typically
3647/// be called in a loop that successively "unwraps" pointer and
3648/// pointer-to-member types to compare them at each level.
3649bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3650 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3651 *T2PtrType = T2->getAs<PointerType>();
3652 if (T1PtrType && T2PtrType) {
3653 T1 = T1PtrType->getPointeeType();
3654 T2 = T2PtrType->getPointeeType();
3655 return true;
3656 }
3657
3658 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3659 *T2MPType = T2->getAs<MemberPointerType>();
3660 if (T1MPType && T2MPType &&
3661 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3662 QualType(T2MPType->getClass(), 0))) {
3663 T1 = T1MPType->getPointeeType();
3664 T2 = T2MPType->getPointeeType();
3665 return true;
3666 }
3667
David Blaikie4e4d0842012-03-11 07:00:24 +00003668 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003669 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3670 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3671 if (T1OPType && T2OPType) {
3672 T1 = T1OPType->getPointeeType();
3673 T2 = T2OPType->getPointeeType();
3674 return true;
3675 }
3676 }
3677
3678 // FIXME: Block pointers, too?
3679
3680 return false;
3681}
3682
Jay Foad4ba2a172011-01-12 09:06:06 +00003683DeclarationNameInfo
3684ASTContext::getNameForTemplate(TemplateName Name,
3685 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003686 switch (Name.getKind()) {
3687 case TemplateName::QualifiedTemplate:
3688 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003689 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003690 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3691 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003692
John McCall14606042011-06-30 08:33:18 +00003693 case TemplateName::OverloadedTemplate: {
3694 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3695 // DNInfo work in progress: CHECKME: what about DNLoc?
3696 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3697 }
3698
3699 case TemplateName::DependentTemplate: {
3700 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003701 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003702 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003703 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3704 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003705 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003706 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3707 // DNInfo work in progress: FIXME: source locations?
3708 DeclarationNameLoc DNLoc;
3709 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3710 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3711 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003712 }
3713 }
3714
John McCall14606042011-06-30 08:33:18 +00003715 case TemplateName::SubstTemplateTemplateParm: {
3716 SubstTemplateTemplateParmStorage *subst
3717 = Name.getAsSubstTemplateTemplateParm();
3718 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3719 NameLoc);
3720 }
3721
3722 case TemplateName::SubstTemplateTemplateParmPack: {
3723 SubstTemplateTemplateParmPackStorage *subst
3724 = Name.getAsSubstTemplateTemplateParmPack();
3725 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3726 NameLoc);
3727 }
3728 }
3729
3730 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003731}
3732
Jay Foad4ba2a172011-01-12 09:06:06 +00003733TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003734 switch (Name.getKind()) {
3735 case TemplateName::QualifiedTemplate:
3736 case TemplateName::Template: {
3737 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003738 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003739 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003740 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3741
3742 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003743 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003744 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003745
John McCall14606042011-06-30 08:33:18 +00003746 case TemplateName::OverloadedTemplate:
3747 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003748
John McCall14606042011-06-30 08:33:18 +00003749 case TemplateName::DependentTemplate: {
3750 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3751 assert(DTN && "Non-dependent template names must refer to template decls.");
3752 return DTN->CanonicalTemplateName;
3753 }
3754
3755 case TemplateName::SubstTemplateTemplateParm: {
3756 SubstTemplateTemplateParmStorage *subst
3757 = Name.getAsSubstTemplateTemplateParm();
3758 return getCanonicalTemplateName(subst->getReplacement());
3759 }
3760
3761 case TemplateName::SubstTemplateTemplateParmPack: {
3762 SubstTemplateTemplateParmPackStorage *subst
3763 = Name.getAsSubstTemplateTemplateParmPack();
3764 TemplateTemplateParmDecl *canonParameter
3765 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3766 TemplateArgument canonArgPack
3767 = getCanonicalTemplateArgument(subst->getArgumentPack());
3768 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3769 }
3770 }
3771
3772 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003773}
3774
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003775bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3776 X = getCanonicalTemplateName(X);
3777 Y = getCanonicalTemplateName(Y);
3778 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3779}
3780
Mike Stump1eb44332009-09-09 15:08:12 +00003781TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003782ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003783 switch (Arg.getKind()) {
3784 case TemplateArgument::Null:
3785 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003786
Douglas Gregor1275ae02009-07-28 23:00:59 +00003787 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003788 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Douglas Gregord2008e22012-04-06 22:40:38 +00003790 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003791 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3792 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003793 }
Mike Stump1eb44332009-09-09 15:08:12 +00003794
Eli Friedmand7a6b162012-09-26 02:36:12 +00003795 case TemplateArgument::NullPtr:
3796 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3797 /*isNullPtr*/true);
3798
Douglas Gregor788cd062009-11-11 01:00:40 +00003799 case TemplateArgument::Template:
3800 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003801
3802 case TemplateArgument::TemplateExpansion:
3803 return TemplateArgument(getCanonicalTemplateName(
3804 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003805 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003806
Douglas Gregor1275ae02009-07-28 23:00:59 +00003807 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003808 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Douglas Gregor1275ae02009-07-28 23:00:59 +00003810 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003811 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003812
Douglas Gregor1275ae02009-07-28 23:00:59 +00003813 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003814 if (Arg.pack_size() == 0)
3815 return Arg;
3816
Douglas Gregor910f8002010-11-07 23:05:16 +00003817 TemplateArgument *CanonArgs
3818 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003819 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003820 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003821 AEnd = Arg.pack_end();
3822 A != AEnd; (void)++A, ++Idx)
3823 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Douglas Gregor910f8002010-11-07 23:05:16 +00003825 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003826 }
3827 }
3828
3829 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003830 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003831}
3832
Douglas Gregord57959a2009-03-27 23:10:48 +00003833NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003834ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003835 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003836 return 0;
3837
3838 switch (NNS->getKind()) {
3839 case NestedNameSpecifier::Identifier:
3840 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003841 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003842 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3843 NNS->getAsIdentifier());
3844
3845 case NestedNameSpecifier::Namespace:
3846 // A namespace is canonical; build a nested-name-specifier with
3847 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003848 return NestedNameSpecifier::Create(*this, 0,
3849 NNS->getAsNamespace()->getOriginalNamespace());
3850
3851 case NestedNameSpecifier::NamespaceAlias:
3852 // A namespace is canonical; build a nested-name-specifier with
3853 // this namespace and no prefix.
3854 return NestedNameSpecifier::Create(*this, 0,
3855 NNS->getAsNamespaceAlias()->getNamespace()
3856 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003857
3858 case NestedNameSpecifier::TypeSpec:
3859 case NestedNameSpecifier::TypeSpecWithTemplate: {
3860 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003861
3862 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3863 // break it apart into its prefix and identifier, then reconsititute those
3864 // as the canonical nested-name-specifier. This is required to canonicalize
3865 // a dependent nested-name-specifier involving typedefs of dependent-name
3866 // types, e.g.,
3867 // typedef typename T::type T1;
3868 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003869 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3870 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003871 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003872
Eli Friedman16412ef2012-03-03 04:09:56 +00003873 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3874 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3875 // first place?
John McCall3b657512011-01-19 10:06:00 +00003876 return NestedNameSpecifier::Create(*this, 0, false,
3877 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003878 }
3879
3880 case NestedNameSpecifier::Global:
3881 // The global specifier is canonical and unique.
3882 return NNS;
3883 }
3884
David Blaikie7530c032012-01-17 06:56:22 +00003885 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003886}
3887
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003888
Jay Foad4ba2a172011-01-12 09:06:06 +00003889const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003890 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003891 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003892 // Handle the common positive case fast.
3893 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3894 return AT;
3895 }
Mike Stump1eb44332009-09-09 15:08:12 +00003896
John McCall0953e762009-09-24 19:53:00 +00003897 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003898 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003899 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003900
John McCall0953e762009-09-24 19:53:00 +00003901 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003902 // implements C99 6.7.3p8: "If the specification of an array type includes
3903 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003905 // If we get here, we either have type qualifiers on the type, or we have
3906 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003907 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003908
John McCall3b657512011-01-19 10:06:00 +00003909 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003910 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003912 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003913 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003914 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003915 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003917 // Otherwise, we have an array and we have qualifiers on it. Push the
3918 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003919 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003920
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003921 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3922 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3923 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003924 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003925 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3926 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3927 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003928 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003929
Mike Stump1eb44332009-09-09 15:08:12 +00003930 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003931 = dyn_cast<DependentSizedArrayType>(ATy))
3932 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003933 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003934 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003935 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003936 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003937 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003938
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003939 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003940 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003941 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003942 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003943 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003944 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003945}
3946
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003947QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003948 // C99 6.7.5.3p7:
3949 // A declaration of a parameter as "array of type" shall be
3950 // adjusted to "qualified pointer to type", where the type
3951 // qualifiers (if any) are those specified within the [ and ] of
3952 // the array type derivation.
3953 if (T->isArrayType())
3954 return getArrayDecayedType(T);
3955
3956 // C99 6.7.5.3p8:
3957 // A declaration of a parameter as "function returning type"
3958 // shall be adjusted to "pointer to function returning type", as
3959 // in 6.3.2.1.
3960 if (T->isFunctionType())
3961 return getPointerType(T);
3962
3963 return T;
3964}
3965
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003966QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003967 T = getVariableArrayDecayedType(T);
3968 T = getAdjustedParameterType(T);
3969 return T.getUnqualifiedType();
3970}
3971
Chris Lattnere6327742008-04-02 05:18:44 +00003972/// getArrayDecayedType - Return the properly qualified result of decaying the
3973/// specified array type to a pointer. This operation is non-trivial when
3974/// handling typedefs etc. The canonical type of "T" must be an array type,
3975/// this returns a pointer to a properly qualified element of the array.
3976///
3977/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003978QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003979 // Get the element type with 'getAsArrayType' so that we don't lose any
3980 // typedefs in the element type of the array. This also handles propagation
3981 // of type qualifiers from the array type into the element type if present
3982 // (C99 6.7.3p8).
3983 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3984 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003986 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003987
3988 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003989 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003990}
3991
John McCall3b657512011-01-19 10:06:00 +00003992QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3993 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003994}
3995
John McCall3b657512011-01-19 10:06:00 +00003996QualType ASTContext::getBaseElementType(QualType type) const {
3997 Qualifiers qs;
3998 while (true) {
3999 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004000 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004001 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004002
John McCall3b657512011-01-19 10:06:00 +00004003 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004004 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004005 }
Mike Stump1eb44332009-09-09 15:08:12 +00004006
John McCall3b657512011-01-19 10:06:00 +00004007 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004008}
4009
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004010/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004011uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004012ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4013 uint64_t ElementCount = 1;
4014 do {
4015 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004016 CA = dyn_cast_or_null<ConstantArrayType>(
4017 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004018 } while (CA);
4019 return ElementCount;
4020}
4021
Reid Spencer5f016e22007-07-11 17:01:13 +00004022/// getFloatingRank - Return a relative rank for floating point types.
4023/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004024static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004025 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004026 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004027
John McCall183700f2009-09-21 23:43:11 +00004028 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4029 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004030 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004031 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004032 case BuiltinType::Float: return FloatRank;
4033 case BuiltinType::Double: return DoubleRank;
4034 case BuiltinType::LongDouble: return LongDoubleRank;
4035 }
4036}
4037
Mike Stump1eb44332009-09-09 15:08:12 +00004038/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4039/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004040/// 'typeDomain' is a real floating point or complex type.
4041/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004042QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4043 QualType Domain) const {
4044 FloatingRank EltRank = getFloatingRank(Size);
4045 if (Domain->isComplexType()) {
4046 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004047 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004048 case FloatRank: return FloatComplexTy;
4049 case DoubleRank: return DoubleComplexTy;
4050 case LongDoubleRank: return LongDoubleComplexTy;
4051 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004052 }
Chris Lattner1361b112008-04-06 23:58:54 +00004053
4054 assert(Domain->isRealFloatingType() && "Unknown domain!");
4055 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004056 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00004057 case FloatRank: return FloatTy;
4058 case DoubleRank: return DoubleTy;
4059 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004060 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004061 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004062}
4063
Chris Lattner7cfeb082008-04-06 23:55:33 +00004064/// getFloatingTypeOrder - Compare the rank of the two specified floating
4065/// point types, ignoring the domain of the type (i.e. 'double' ==
4066/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004067/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004068int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004069 FloatingRank LHSR = getFloatingRank(LHS);
4070 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004071
Chris Lattnera75cea32008-04-06 23:38:49 +00004072 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004073 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004074 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004075 return 1;
4076 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004077}
4078
Chris Lattnerf52ab252008-04-06 22:59:24 +00004079/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4080/// routine will assert if passed a built-in type that isn't an integer or enum,
4081/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004082unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004083 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004084
Chris Lattnerf52ab252008-04-06 22:59:24 +00004085 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004086 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004087 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004088 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004089 case BuiltinType::Char_S:
4090 case BuiltinType::Char_U:
4091 case BuiltinType::SChar:
4092 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004093 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004094 case BuiltinType::Short:
4095 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004096 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004097 case BuiltinType::Int:
4098 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004099 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004100 case BuiltinType::Long:
4101 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004102 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004103 case BuiltinType::LongLong:
4104 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004105 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004106 case BuiltinType::Int128:
4107 case BuiltinType::UInt128:
4108 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004109 }
4110}
4111
Eli Friedman04e83572009-08-20 04:21:42 +00004112/// \brief Whether this is a promotable bitfield reference according
4113/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4114///
4115/// \returns the type this bit-field will promote to, or NULL if no
4116/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004117QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004118 if (E->isTypeDependent() || E->isValueDependent())
4119 return QualType();
4120
Eli Friedman04e83572009-08-20 04:21:42 +00004121 FieldDecl *Field = E->getBitField();
4122 if (!Field)
4123 return QualType();
4124
4125 QualType FT = Field->getType();
4126
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004127 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004128 uint64_t IntSize = getTypeSize(IntTy);
4129 // GCC extension compatibility: if the bit-field size is less than or equal
4130 // to the size of int, it gets promoted no matter what its type is.
4131 // For instance, unsigned long bf : 4 gets promoted to signed int.
4132 if (BitWidth < IntSize)
4133 return IntTy;
4134
4135 if (BitWidth == IntSize)
4136 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4137
4138 // Types bigger than int are not subject to promotions, and therefore act
4139 // like the base type.
4140 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4141 // is ridiculous.
4142 return QualType();
4143}
4144
Eli Friedmana95d7572009-08-19 07:44:53 +00004145/// getPromotedIntegerType - Returns the type that Promotable will
4146/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4147/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004148QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004149 assert(!Promotable.isNull());
4150 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004151 if (const EnumType *ET = Promotable->getAs<EnumType>())
4152 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004153
4154 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4155 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4156 // (3.9.1) can be converted to a prvalue of the first of the following
4157 // types that can represent all the values of its underlying type:
4158 // int, unsigned int, long int, unsigned long int, long long int, or
4159 // unsigned long long int [...]
4160 // FIXME: Is there some better way to compute this?
4161 if (BT->getKind() == BuiltinType::WChar_S ||
4162 BT->getKind() == BuiltinType::WChar_U ||
4163 BT->getKind() == BuiltinType::Char16 ||
4164 BT->getKind() == BuiltinType::Char32) {
4165 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4166 uint64_t FromSize = getTypeSize(BT);
4167 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4168 LongLongTy, UnsignedLongLongTy };
4169 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4170 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4171 if (FromSize < ToSize ||
4172 (FromSize == ToSize &&
4173 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4174 return PromoteTypes[Idx];
4175 }
4176 llvm_unreachable("char type should fit into long long");
4177 }
4178 }
4179
4180 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004181 if (Promotable->isSignedIntegerType())
4182 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004183 uint64_t PromotableSize = getIntWidth(Promotable);
4184 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004185 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4186 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4187}
4188
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004189/// \brief Recurses in pointer/array types until it finds an objc retainable
4190/// type and returns its ownership.
4191Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4192 while (!T.isNull()) {
4193 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4194 return T.getObjCLifetime();
4195 if (T->isArrayType())
4196 T = getBaseElementType(T);
4197 else if (const PointerType *PT = T->getAs<PointerType>())
4198 T = PT->getPointeeType();
4199 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004200 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004201 else
4202 break;
4203 }
4204
4205 return Qualifiers::OCL_None;
4206}
4207
Mike Stump1eb44332009-09-09 15:08:12 +00004208/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004209/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004210/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004211int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004212 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4213 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004214 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004215
Chris Lattnerf52ab252008-04-06 22:59:24 +00004216 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4217 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Chris Lattner7cfeb082008-04-06 23:55:33 +00004219 unsigned LHSRank = getIntegerRank(LHSC);
4220 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004221
Chris Lattner7cfeb082008-04-06 23:55:33 +00004222 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4223 if (LHSRank == RHSRank) return 0;
4224 return LHSRank > RHSRank ? 1 : -1;
4225 }
Mike Stump1eb44332009-09-09 15:08:12 +00004226
Chris Lattner7cfeb082008-04-06 23:55:33 +00004227 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4228 if (LHSUnsigned) {
4229 // If the unsigned [LHS] type is larger, return it.
4230 if (LHSRank >= RHSRank)
4231 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Chris Lattner7cfeb082008-04-06 23:55:33 +00004233 // If the signed type can represent all values of the unsigned type, it
4234 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004235 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004236 return -1;
4237 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004238
Chris Lattner7cfeb082008-04-06 23:55:33 +00004239 // If the unsigned [RHS] type is larger, return it.
4240 if (RHSRank >= LHSRank)
4241 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004242
Chris Lattner7cfeb082008-04-06 23:55:33 +00004243 // If the signed type can represent all values of the unsigned type, it
4244 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004245 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004246 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004247}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004248
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004249static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004250CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4251 DeclContext *DC, IdentifierInfo *Id) {
4252 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004253 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004254 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004255 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004256 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004257}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004258
Mike Stump1eb44332009-09-09 15:08:12 +00004259// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004260QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004261 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004262 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004263 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004264 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004265 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004266
Anders Carlssonf06273f2007-11-19 00:25:30 +00004267 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Anders Carlsson71993dd2007-08-17 05:31:46 +00004269 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004270 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004271 // int flags;
4272 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004273 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004274 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004275 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004276 FieldTypes[3] = LongTy;
4277
Anders Carlsson71993dd2007-08-17 05:31:46 +00004278 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004279 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004280 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004281 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004282 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004283 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004284 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004285 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004286 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004287 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004288 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004289 }
4290
Douglas Gregor838db382010-02-11 01:19:42 +00004291 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004292 }
Mike Stump1eb44332009-09-09 15:08:12 +00004293
Anders Carlsson71993dd2007-08-17 05:31:46 +00004294 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004295}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004296
Douglas Gregor319ac892009-04-23 22:29:11 +00004297void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004298 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004299 assert(Rec && "Invalid CFConstantStringType");
4300 CFConstantStringTypeDecl = Rec->getDecl();
4301}
4302
Jay Foad4ba2a172011-01-12 09:06:06 +00004303QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004304 if (BlockDescriptorType)
4305 return getTagDeclType(BlockDescriptorType);
4306
4307 RecordDecl *T;
4308 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004309 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004310 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004311 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004312
4313 QualType FieldTypes[] = {
4314 UnsignedLongTy,
4315 UnsignedLongTy,
4316 };
4317
4318 const char *FieldNames[] = {
4319 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004320 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004321 };
4322
4323 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004324 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004325 SourceLocation(),
4326 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004327 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004328 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004329 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004330 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004331 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004332 T->addDecl(Field);
4333 }
4334
Douglas Gregor838db382010-02-11 01:19:42 +00004335 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004336
4337 BlockDescriptorType = T;
4338
4339 return getTagDeclType(BlockDescriptorType);
4340}
4341
Jay Foad4ba2a172011-01-12 09:06:06 +00004342QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004343 if (BlockDescriptorExtendedType)
4344 return getTagDeclType(BlockDescriptorExtendedType);
4345
4346 RecordDecl *T;
4347 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004348 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004349 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004350 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004351
4352 QualType FieldTypes[] = {
4353 UnsignedLongTy,
4354 UnsignedLongTy,
4355 getPointerType(VoidPtrTy),
4356 getPointerType(VoidPtrTy)
4357 };
4358
4359 const char *FieldNames[] = {
4360 "reserved",
4361 "Size",
4362 "CopyFuncPtr",
4363 "DestroyFuncPtr"
4364 };
4365
4366 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004367 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004368 SourceLocation(),
4369 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004370 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004371 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004372 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004373 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004374 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004375 T->addDecl(Field);
4376 }
4377
Douglas Gregor838db382010-02-11 01:19:42 +00004378 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004379
4380 BlockDescriptorExtendedType = T;
4381
4382 return getTagDeclType(BlockDescriptorExtendedType);
4383}
4384
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004385/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4386/// requires copy/dispose. Note that this must match the logic
4387/// in buildByrefHelpers.
4388bool ASTContext::BlockRequiresCopying(QualType Ty,
4389 const VarDecl *D) {
4390 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4391 const Expr *copyExpr = getBlockVarCopyInits(D);
4392 if (!copyExpr && record->hasTrivialDestructor()) return false;
4393
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004394 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004395 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004396
4397 if (!Ty->isObjCRetainableType()) return false;
4398
4399 Qualifiers qs = Ty.getQualifiers();
4400
4401 // If we have lifetime, that dominates.
4402 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4403 assert(getLangOpts().ObjCAutoRefCount);
4404
4405 switch (lifetime) {
4406 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4407
4408 // These are just bits as far as the runtime is concerned.
4409 case Qualifiers::OCL_ExplicitNone:
4410 case Qualifiers::OCL_Autoreleasing:
4411 return false;
4412
4413 // Tell the runtime that this is ARC __weak, called by the
4414 // byref routines.
4415 case Qualifiers::OCL_Weak:
4416 // ARC __strong __block variables need to be retained.
4417 case Qualifiers::OCL_Strong:
4418 return true;
4419 }
4420 llvm_unreachable("fell out of lifetime switch!");
4421 }
4422 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4423 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004424}
4425
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004426bool ASTContext::getByrefLifetime(QualType Ty,
4427 Qualifiers::ObjCLifetime &LifeTime,
4428 bool &HasByrefExtendedLayout) const {
4429
4430 if (!getLangOpts().ObjC1 ||
4431 getLangOpts().getGC() != LangOptions::NonGC)
4432 return false;
4433
4434 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004435 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004436 HasByrefExtendedLayout = true;
4437 LifeTime = Qualifiers::OCL_None;
4438 }
4439 else if (getLangOpts().ObjCAutoRefCount)
4440 LifeTime = Ty.getObjCLifetime();
4441 // MRR.
4442 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4443 LifeTime = Qualifiers::OCL_ExplicitNone;
4444 else
4445 LifeTime = Qualifiers::OCL_None;
4446 return true;
4447}
4448
Douglas Gregore97179c2011-09-08 01:46:34 +00004449TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4450 if (!ObjCInstanceTypeDecl)
4451 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4452 getTranslationUnitDecl(),
4453 SourceLocation(),
4454 SourceLocation(),
4455 &Idents.get("instancetype"),
4456 getTrivialTypeSourceInfo(getObjCIdType()));
4457 return ObjCInstanceTypeDecl;
4458}
4459
Anders Carlssone8c49532007-10-29 06:33:42 +00004460// This returns true if a type has been typedefed to BOOL:
4461// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004462static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004463 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004464 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4465 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004466
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004467 return false;
4468}
4469
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004470/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004471/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004472CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004473 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4474 return CharUnits::Zero();
4475
Ken Dyck199c3d62010-01-11 17:06:35 +00004476 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004478 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004479 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004480 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004481 // Treat arrays as pointers, since that's how they're passed in.
4482 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004483 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004484 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004485}
4486
4487static inline
4488std::string charUnitsToString(const CharUnits &CU) {
4489 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004490}
4491
John McCall6b5a61b2011-02-07 10:33:21 +00004492/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004493/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004494std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4495 std::string S;
4496
David Chisnall5e530af2009-11-17 19:33:30 +00004497 const BlockDecl *Decl = Expr->getBlockDecl();
4498 QualType BlockTy =
4499 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4500 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004501 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004502 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4503 BlockTy->getAs<FunctionType>()->getResultType(),
4504 S, true /*Extended*/);
4505 else
4506 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4507 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004508 // Compute size of all parameters.
4509 // Start with computing size of a pointer in number of bytes.
4510 // FIXME: There might(should) be a better way of doing this computation!
4511 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004512 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4513 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004514 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004515 E = Decl->param_end(); PI != E; ++PI) {
4516 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004517 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004518 if (sz.isZero())
4519 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004520 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004521 ParmOffset += sz;
4522 }
4523 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004524 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004525 // Block pointer and offset.
4526 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004527
4528 // Argument types.
4529 ParmOffset = PtrSize;
4530 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4531 Decl->param_end(); PI != E; ++PI) {
4532 ParmVarDecl *PVDecl = *PI;
4533 QualType PType = PVDecl->getOriginalType();
4534 if (const ArrayType *AT =
4535 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4536 // Use array's original type only if it has known number of
4537 // elements.
4538 if (!isa<ConstantArrayType>(AT))
4539 PType = PVDecl->getType();
4540 } else if (PType->isFunctionType())
4541 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004542 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004543 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4544 S, true /*Extended*/);
4545 else
4546 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004547 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004548 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004549 }
John McCall6b5a61b2011-02-07 10:33:21 +00004550
4551 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004552}
4553
Douglas Gregorf968d832011-05-27 01:19:52 +00004554bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004555 std::string& S) {
4556 // Encode result type.
4557 getObjCEncodingForType(Decl->getResultType(), S);
4558 CharUnits ParmOffset;
4559 // Compute size of all parameters.
4560 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4561 E = Decl->param_end(); PI != E; ++PI) {
4562 QualType PType = (*PI)->getType();
4563 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004564 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004565 continue;
4566
David Chisnall5389f482010-12-30 14:05:53 +00004567 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004568 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004569 ParmOffset += sz;
4570 }
4571 S += charUnitsToString(ParmOffset);
4572 ParmOffset = CharUnits::Zero();
4573
4574 // Argument types.
4575 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4576 E = Decl->param_end(); PI != E; ++PI) {
4577 ParmVarDecl *PVDecl = *PI;
4578 QualType PType = PVDecl->getOriginalType();
4579 if (const ArrayType *AT =
4580 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4581 // Use array's original type only if it has known number of
4582 // elements.
4583 if (!isa<ConstantArrayType>(AT))
4584 PType = PVDecl->getType();
4585 } else if (PType->isFunctionType())
4586 PType = PVDecl->getType();
4587 getObjCEncodingForType(PType, S);
4588 S += charUnitsToString(ParmOffset);
4589 ParmOffset += getObjCEncodingTypeSize(PType);
4590 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004591
4592 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004593}
4594
Bob Wilsondc8dab62011-11-30 01:57:58 +00004595/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4596/// method parameter or return type. If Extended, include class names and
4597/// block object types.
4598void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4599 QualType T, std::string& S,
4600 bool Extended) const {
4601 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4602 getObjCEncodingForTypeQualifier(QT, S);
4603 // Encode parameter type.
4604 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4605 true /*OutermostType*/,
4606 false /*EncodingProperty*/,
4607 false /*StructField*/,
4608 Extended /*EncodeBlockParameters*/,
4609 Extended /*EncodeClassNames*/);
4610}
4611
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004612/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004613/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004614bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004615 std::string& S,
4616 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004617 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004618 // Encode return type.
4619 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4620 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004621 // Compute size of all parameters.
4622 // Start with computing size of a pointer in number of bytes.
4623 // FIXME: There might(should) be a better way of doing this computation!
4624 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004625 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004626 // The first two arguments (self and _cmd) are pointers; account for
4627 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004628 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004629 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004630 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004631 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004632 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004633 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004634 continue;
4635
Ken Dyck199c3d62010-01-11 17:06:35 +00004636 assert (sz.isPositive() &&
4637 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004638 ParmOffset += sz;
4639 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004640 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004641 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004642 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004643
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004644 // Argument types.
4645 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004646 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004647 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004648 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004649 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004650 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004651 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4652 // Use array's original type only if it has known number of
4653 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004654 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004655 PType = PVDecl->getType();
4656 } else if (PType->isFunctionType())
4657 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004658 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4659 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004660 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004661 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004662 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004663
4664 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004665}
4666
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004667/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004668/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004669/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4670/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004671/// Property attributes are stored as a comma-delimited C string. The simple
4672/// attributes readonly and bycopy are encoded as single characters. The
4673/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4674/// encoded as single characters, followed by an identifier. Property types
4675/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004676/// these attributes are defined by the following enumeration:
4677/// @code
4678/// enum PropertyAttributes {
4679/// kPropertyReadOnly = 'R', // property is read-only.
4680/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4681/// kPropertyByref = '&', // property is a reference to the value last assigned
4682/// kPropertyDynamic = 'D', // property is dynamic
4683/// kPropertyGetter = 'G', // followed by getter selector name
4684/// kPropertySetter = 'S', // followed by setter selector name
4685/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004686/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004687/// kPropertyWeak = 'W' // 'weak' property
4688/// kPropertyStrong = 'P' // property GC'able
4689/// kPropertyNonAtomic = 'N' // property non-atomic
4690/// };
4691/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004692void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004693 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004694 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004695 // Collect information from the property implementation decl(s).
4696 bool Dynamic = false;
4697 ObjCPropertyImplDecl *SynthesizePID = 0;
4698
4699 // FIXME: Duplicated code due to poor abstraction.
4700 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004701 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004702 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4703 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004704 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004705 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004706 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004707 if (PID->getPropertyDecl() == PD) {
4708 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4709 Dynamic = true;
4710 } else {
4711 SynthesizePID = PID;
4712 }
4713 }
4714 }
4715 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004716 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004717 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004718 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004719 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004720 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004721 if (PID->getPropertyDecl() == PD) {
4722 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4723 Dynamic = true;
4724 } else {
4725 SynthesizePID = PID;
4726 }
4727 }
Mike Stump1eb44332009-09-09 15:08:12 +00004728 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004729 }
4730 }
4731
4732 // FIXME: This is not very efficient.
4733 S = "T";
4734
4735 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004736 // GCC has some special rules regarding encoding of properties which
4737 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004738 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004739 true /* outermost type */,
4740 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004741
4742 if (PD->isReadOnly()) {
4743 S += ",R";
4744 } else {
4745 switch (PD->getSetterKind()) {
4746 case ObjCPropertyDecl::Assign: break;
4747 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004748 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004749 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004750 }
4751 }
4752
4753 // It really isn't clear at all what this means, since properties
4754 // are "dynamic by default".
4755 if (Dynamic)
4756 S += ",D";
4757
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004758 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4759 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004761 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4762 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004763 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004764 }
4765
4766 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4767 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004768 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004769 }
4770
4771 if (SynthesizePID) {
4772 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4773 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004774 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004775 }
4776
4777 // FIXME: OBJCGC: weak & strong
4778}
4779
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004780/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004781/// Another legacy compatibility encoding: 32-bit longs are encoded as
4782/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004783/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4784///
4785void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004786 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004787 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004788 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004789 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004790 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004791 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004792 PointeeTy = IntTy;
4793 }
4794 }
4795}
4796
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004797void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004798 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004799 // We follow the behavior of gcc, expanding structures which are
4800 // directly pointed to, and expanding embedded structures. Note that
4801 // these rules are sufficient to prevent recursive encoding of the
4802 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004803 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004804 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004805}
4806
John McCall3624e9e2012-12-20 02:45:14 +00004807static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4808 BuiltinType::Kind kind) {
4809 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004810 case BuiltinType::Void: return 'v';
4811 case BuiltinType::Bool: return 'B';
4812 case BuiltinType::Char_U:
4813 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00004814 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00004815 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00004816 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00004817 case BuiltinType::UInt: return 'I';
4818 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00004819 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004820 case BuiltinType::UInt128: return 'T';
4821 case BuiltinType::ULongLong: return 'Q';
4822 case BuiltinType::Char_S:
4823 case BuiltinType::SChar: return 'c';
4824 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004825 case BuiltinType::WChar_S:
4826 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004827 case BuiltinType::Int: return 'i';
4828 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00004829 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004830 case BuiltinType::LongLong: return 'q';
4831 case BuiltinType::Int128: return 't';
4832 case BuiltinType::Float: return 'f';
4833 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004834 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00004835 case BuiltinType::NullPtr: return '*'; // like char*
4836
4837 case BuiltinType::Half:
4838 // FIXME: potentially need @encodes for these!
4839 return ' ';
4840
4841 case BuiltinType::ObjCId:
4842 case BuiltinType::ObjCClass:
4843 case BuiltinType::ObjCSel:
4844 llvm_unreachable("@encoding ObjC primitive type");
4845
4846 // OpenCL and placeholder types don't need @encodings.
4847 case BuiltinType::OCLImage1d:
4848 case BuiltinType::OCLImage1dArray:
4849 case BuiltinType::OCLImage1dBuffer:
4850 case BuiltinType::OCLImage2d:
4851 case BuiltinType::OCLImage2dArray:
4852 case BuiltinType::OCLImage3d:
4853 case BuiltinType::Dependent:
4854#define BUILTIN_TYPE(KIND, ID)
4855#define PLACEHOLDER_TYPE(KIND, ID) \
4856 case BuiltinType::KIND:
4857#include "clang/AST/BuiltinTypes.def"
4858 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00004859 }
4860}
4861
Douglas Gregor5471bc82011-09-08 17:18:35 +00004862static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4863 EnumDecl *Enum = ET->getDecl();
4864
4865 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4866 if (!Enum->isFixed())
4867 return 'i';
4868
4869 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00004870 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4871 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00004872}
4873
Jay Foad4ba2a172011-01-12 09:06:06 +00004874static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004875 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004876 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004877 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004878 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4879 // The GNU runtime requires more information; bitfields are encoded as b,
4880 // then the offset (in bits) of the first element, then the type of the
4881 // bitfield, then the size in bits. For example, in this structure:
4882 //
4883 // struct
4884 // {
4885 // int integer;
4886 // int flags:2;
4887 // };
4888 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4889 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4890 // information is not especially sensible, but we're stuck with it for
4891 // compatibility with GCC, although providing it breaks anything that
4892 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004893 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004894 const RecordDecl *RD = FD->getParent();
4895 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004896 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004897 if (const EnumType *ET = T->getAs<EnumType>())
4898 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00004899 else {
4900 const BuiltinType *BT = T->castAs<BuiltinType>();
4901 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4902 }
David Chisnall64fd7e82010-06-04 01:10:52 +00004903 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004904 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004905}
4906
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004907// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004908void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4909 bool ExpandPointedToStructures,
4910 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004911 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004912 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004913 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004914 bool StructField,
4915 bool EncodeBlockParameters,
4916 bool EncodeClassNames) const {
John McCall3624e9e2012-12-20 02:45:14 +00004917 CanQualType CT = getCanonicalType(T);
4918 switch (CT->getTypeClass()) {
4919 case Type::Builtin:
4920 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004921 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004922 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00004923 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4924 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4925 else
4926 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004927 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004928
John McCall3624e9e2012-12-20 02:45:14 +00004929 case Type::Complex: {
4930 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004931 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004932 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004933 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004934 return;
4935 }
John McCall3624e9e2012-12-20 02:45:14 +00004936
4937 case Type::Atomic: {
4938 const AtomicType *AT = T->castAs<AtomicType>();
4939 S += 'A';
4940 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
4941 false, false);
4942 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004943 }
John McCall3624e9e2012-12-20 02:45:14 +00004944
4945 // encoding for pointer or reference types.
4946 case Type::Pointer:
4947 case Type::LValueReference:
4948 case Type::RValueReference: {
4949 QualType PointeeTy;
4950 if (isa<PointerType>(CT)) {
4951 const PointerType *PT = T->castAs<PointerType>();
4952 if (PT->isObjCSelType()) {
4953 S += ':';
4954 return;
4955 }
4956 PointeeTy = PT->getPointeeType();
4957 } else {
4958 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
4959 }
4960
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004961 bool isReadOnly = false;
4962 // For historical/compatibility reasons, the read-only qualifier of the
4963 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4964 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004965 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004966 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004967 if (OutermostType && T.isConstQualified()) {
4968 isReadOnly = true;
4969 S += 'r';
4970 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004971 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004972 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004973 while (P->getAs<PointerType>())
4974 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004975 if (P.isConstQualified()) {
4976 isReadOnly = true;
4977 S += 'r';
4978 }
4979 }
4980 if (isReadOnly) {
4981 // Another legacy compatibility encoding. Some ObjC qualifier and type
4982 // combinations need to be rearranged.
4983 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004984 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004985 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004986 }
Mike Stump1eb44332009-09-09 15:08:12 +00004987
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004988 if (PointeeTy->isCharType()) {
4989 // char pointer types should be encoded as '*' unless it is a
4990 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004991 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004992 S += '*';
4993 return;
4994 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004995 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004996 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4997 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4998 S += '#';
4999 return;
5000 }
5001 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5002 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5003 S += '@';
5004 return;
5005 }
5006 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005007 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005008 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005009 getLegacyIntegralTypeEncoding(PointeeTy);
5010
Mike Stump1eb44332009-09-09 15:08:12 +00005011 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005012 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005013 return;
5014 }
John McCall3624e9e2012-12-20 02:45:14 +00005015
5016 case Type::ConstantArray:
5017 case Type::IncompleteArray:
5018 case Type::VariableArray: {
5019 const ArrayType *AT = cast<ArrayType>(CT);
5020
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005021 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005022 // Incomplete arrays are encoded as a pointer to the array element.
5023 S += '^';
5024
Mike Stump1eb44332009-09-09 15:08:12 +00005025 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005026 false, ExpandStructures, FD);
5027 } else {
5028 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005029
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005030 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5031 if (getTypeSize(CAT->getElementType()) == 0)
5032 S += '0';
5033 else
5034 S += llvm::utostr(CAT->getSize().getZExtValue());
5035 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005036 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005037 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5038 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005039 S += '0';
5040 }
Mike Stump1eb44332009-09-09 15:08:12 +00005041
5042 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005043 false, ExpandStructures, FD);
5044 S += ']';
5045 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005046 return;
5047 }
Mike Stump1eb44332009-09-09 15:08:12 +00005048
John McCall3624e9e2012-12-20 02:45:14 +00005049 case Type::FunctionNoProto:
5050 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005051 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005052 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005053
John McCall3624e9e2012-12-20 02:45:14 +00005054 case Type::Record: {
5055 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005056 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005057 // Anonymous structures print as '?'
5058 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5059 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005060 if (ClassTemplateSpecializationDecl *Spec
5061 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5062 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5063 std::string TemplateArgsStr
5064 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00005065 TemplateArgs.data(),
5066 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005067 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005068
5069 S += TemplateArgsStr;
5070 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005071 } else {
5072 S += '?';
5073 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005074 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005075 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005076 if (!RDecl->isUnion()) {
5077 getObjCEncodingForStructureImpl(RDecl, S, FD);
5078 } else {
5079 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5080 FieldEnd = RDecl->field_end();
5081 Field != FieldEnd; ++Field) {
5082 if (FD) {
5083 S += '"';
5084 S += Field->getNameAsString();
5085 S += '"';
5086 }
Mike Stump1eb44332009-09-09 15:08:12 +00005087
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005088 // Special case bit-fields.
5089 if (Field->isBitField()) {
5090 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005091 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005092 } else {
5093 QualType qt = Field->getType();
5094 getLegacyIntegralTypeEncoding(qt);
5095 getObjCEncodingForTypeImpl(qt, S, false, true,
5096 FD, /*OutermostType*/false,
5097 /*EncodingProperty*/false,
5098 /*StructField*/true);
5099 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005100 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005101 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005102 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005103 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005104 return;
5105 }
Mike Stump1eb44332009-09-09 15:08:12 +00005106
John McCall3624e9e2012-12-20 02:45:14 +00005107 case Type::BlockPointer: {
5108 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005109 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005110 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005111 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005112
5113 S += '<';
5114 // Block return type
5115 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5116 ExpandPointedToStructures, ExpandStructures,
5117 FD,
5118 false /* OutermostType */,
5119 EncodingProperty,
5120 false /* StructField */,
5121 EncodeBlockParameters,
5122 EncodeClassNames);
5123 // Block self
5124 S += "@?";
5125 // Block parameters
5126 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5127 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5128 E = FPT->arg_type_end(); I && (I != E); ++I) {
5129 getObjCEncodingForTypeImpl(*I, S,
5130 ExpandPointedToStructures,
5131 ExpandStructures,
5132 FD,
5133 false /* OutermostType */,
5134 EncodingProperty,
5135 false /* StructField */,
5136 EncodeBlockParameters,
5137 EncodeClassNames);
5138 }
5139 }
5140 S += '>';
5141 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005142 return;
5143 }
Mike Stump1eb44332009-09-09 15:08:12 +00005144
John McCall3624e9e2012-12-20 02:45:14 +00005145 case Type::ObjCObject:
5146 case Type::ObjCInterface: {
5147 // Ignore protocol qualifiers when mangling at this level.
5148 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005149
John McCall3624e9e2012-12-20 02:45:14 +00005150 // The assumption seems to be that this assert will succeed
5151 // because nested levels will have filtered out 'id' and 'Class'.
5152 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005153 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005154 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005155 S += '{';
5156 const IdentifierInfo *II = OI->getIdentifier();
5157 S += II->getName();
5158 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005159 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005160 DeepCollectObjCIvars(OI, true, Ivars);
5161 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005162 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005163 if (Field->isBitField())
5164 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005165 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005166 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005167 }
5168 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005169 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005170 }
Mike Stump1eb44332009-09-09 15:08:12 +00005171
John McCall3624e9e2012-12-20 02:45:14 +00005172 case Type::ObjCObjectPointer: {
5173 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005174 if (OPT->isObjCIdType()) {
5175 S += '@';
5176 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005177 }
Mike Stump1eb44332009-09-09 15:08:12 +00005178
Steve Naroff27d20a22009-10-28 22:03:49 +00005179 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5180 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5181 // Since this is a binary compatibility issue, need to consult with runtime
5182 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005183 S += '#';
5184 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005185 }
Mike Stump1eb44332009-09-09 15:08:12 +00005186
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005187 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005188 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005189 ExpandPointedToStructures,
5190 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005191 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005192 // Note that we do extended encoding of protocol qualifer list
5193 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005194 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005195 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5196 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005197 S += '<';
5198 S += (*I)->getNameAsString();
5199 S += '>';
5200 }
5201 S += '"';
5202 }
5203 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005204 }
Mike Stump1eb44332009-09-09 15:08:12 +00005205
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005206 QualType PointeeTy = OPT->getPointeeType();
5207 if (!EncodingProperty &&
5208 isa<TypedefType>(PointeeTy.getTypePtr())) {
5209 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005210 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005211 // {...};
5212 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005213 getObjCEncodingForTypeImpl(PointeeTy, S,
5214 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005215 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00005216 return;
5217 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005218
5219 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005220 if (OPT->getInterfaceDecl() &&
5221 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005222 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005223 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005224 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5225 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005226 S += '<';
5227 S += (*I)->getNameAsString();
5228 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005229 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005230 S += '"';
5231 }
5232 return;
5233 }
Mike Stump1eb44332009-09-09 15:08:12 +00005234
John McCall532ec7b2010-05-17 23:56:34 +00005235 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005236 // FIXME: we shoul do better than that. 'M' is available.
5237 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005238 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005239
John McCall3624e9e2012-12-20 02:45:14 +00005240 case Type::Vector:
5241 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005242 // This matches gcc's encoding, even though technically it is
5243 // insufficient.
5244 // FIXME. We should do a better job than gcc.
5245 return;
John McCall3624e9e2012-12-20 02:45:14 +00005246
5247#define ABSTRACT_TYPE(KIND, BASE)
5248#define TYPE(KIND, BASE)
5249#define DEPENDENT_TYPE(KIND, BASE) \
5250 case Type::KIND:
5251#define NON_CANONICAL_TYPE(KIND, BASE) \
5252 case Type::KIND:
5253#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5254 case Type::KIND:
5255#include "clang/AST/TypeNodes.def"
5256 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005257 }
John McCall3624e9e2012-12-20 02:45:14 +00005258 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005259}
5260
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005261void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5262 std::string &S,
5263 const FieldDecl *FD,
5264 bool includeVBases) const {
5265 assert(RDecl && "Expected non-null RecordDecl");
5266 assert(!RDecl->isUnion() && "Should not be called for unions");
5267 if (!RDecl->getDefinition())
5268 return;
5269
5270 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5271 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5272 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5273
5274 if (CXXRec) {
5275 for (CXXRecordDecl::base_class_iterator
5276 BI = CXXRec->bases_begin(),
5277 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5278 if (!BI->isVirtual()) {
5279 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005280 if (base->isEmpty())
5281 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005282 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005283 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5284 std::make_pair(offs, base));
5285 }
5286 }
5287 }
5288
5289 unsigned i = 0;
5290 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5291 FieldEnd = RDecl->field_end();
5292 Field != FieldEnd; ++Field, ++i) {
5293 uint64_t offs = layout.getFieldOffset(i);
5294 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005295 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005296 }
5297
5298 if (CXXRec && includeVBases) {
5299 for (CXXRecordDecl::base_class_iterator
5300 BI = CXXRec->vbases_begin(),
5301 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5302 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005303 if (base->isEmpty())
5304 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005305 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005306 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5307 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5308 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005309 }
5310 }
5311
5312 CharUnits size;
5313 if (CXXRec) {
5314 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5315 } else {
5316 size = layout.getSize();
5317 }
5318
5319 uint64_t CurOffs = 0;
5320 std::multimap<uint64_t, NamedDecl *>::iterator
5321 CurLayObj = FieldOrBaseOffsets.begin();
5322
Douglas Gregor58db7a52012-04-27 22:30:01 +00005323 if (CXXRec && CXXRec->isDynamicClass() &&
5324 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005325 if (FD) {
5326 S += "\"_vptr$";
5327 std::string recname = CXXRec->getNameAsString();
5328 if (recname.empty()) recname = "?";
5329 S += recname;
5330 S += '"';
5331 }
5332 S += "^^?";
5333 CurOffs += getTypeSize(VoidPtrTy);
5334 }
5335
5336 if (!RDecl->hasFlexibleArrayMember()) {
5337 // Mark the end of the structure.
5338 uint64_t offs = toBits(size);
5339 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5340 std::make_pair(offs, (NamedDecl*)0));
5341 }
5342
5343 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5344 assert(CurOffs <= CurLayObj->first);
5345
5346 if (CurOffs < CurLayObj->first) {
5347 uint64_t padding = CurLayObj->first - CurOffs;
5348 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5349 // packing/alignment of members is different that normal, in which case
5350 // the encoding will be out-of-sync with the real layout.
5351 // If the runtime switches to just consider the size of types without
5352 // taking into account alignment, we could make padding explicit in the
5353 // encoding (e.g. using arrays of chars). The encoding strings would be
5354 // longer then though.
5355 CurOffs += padding;
5356 }
5357
5358 NamedDecl *dcl = CurLayObj->second;
5359 if (dcl == 0)
5360 break; // reached end of structure.
5361
5362 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5363 // We expand the bases without their virtual bases since those are going
5364 // in the initial structure. Note that this differs from gcc which
5365 // expands virtual bases each time one is encountered in the hierarchy,
5366 // making the encoding type bigger than it really is.
5367 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005368 assert(!base->isEmpty());
5369 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005370 } else {
5371 FieldDecl *field = cast<FieldDecl>(dcl);
5372 if (FD) {
5373 S += '"';
5374 S += field->getNameAsString();
5375 S += '"';
5376 }
5377
5378 if (field->isBitField()) {
5379 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005380 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005381 } else {
5382 QualType qt = field->getType();
5383 getLegacyIntegralTypeEncoding(qt);
5384 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5385 /*OutermostType*/false,
5386 /*EncodingProperty*/false,
5387 /*StructField*/true);
5388 CurOffs += getTypeSize(field->getType());
5389 }
5390 }
5391 }
5392}
5393
Mike Stump1eb44332009-09-09 15:08:12 +00005394void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005395 std::string& S) const {
5396 if (QT & Decl::OBJC_TQ_In)
5397 S += 'n';
5398 if (QT & Decl::OBJC_TQ_Inout)
5399 S += 'N';
5400 if (QT & Decl::OBJC_TQ_Out)
5401 S += 'o';
5402 if (QT & Decl::OBJC_TQ_Bycopy)
5403 S += 'O';
5404 if (QT & Decl::OBJC_TQ_Byref)
5405 S += 'R';
5406 if (QT & Decl::OBJC_TQ_Oneway)
5407 S += 'V';
5408}
5409
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005410TypedefDecl *ASTContext::getObjCIdDecl() const {
5411 if (!ObjCIdDecl) {
5412 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5413 T = getObjCObjectPointerType(T);
5414 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5415 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5416 getTranslationUnitDecl(),
5417 SourceLocation(), SourceLocation(),
5418 &Idents.get("id"), IdInfo);
5419 }
5420
5421 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005422}
5423
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005424TypedefDecl *ASTContext::getObjCSelDecl() const {
5425 if (!ObjCSelDecl) {
5426 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5427 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5428 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5429 getTranslationUnitDecl(),
5430 SourceLocation(), SourceLocation(),
5431 &Idents.get("SEL"), SelInfo);
5432 }
5433 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005434}
5435
Douglas Gregor79d67262011-08-12 05:59:41 +00005436TypedefDecl *ASTContext::getObjCClassDecl() const {
5437 if (!ObjCClassDecl) {
5438 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5439 T = getObjCObjectPointerType(T);
5440 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5441 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5442 getTranslationUnitDecl(),
5443 SourceLocation(), SourceLocation(),
5444 &Idents.get("Class"), ClassInfo);
5445 }
5446
5447 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005448}
5449
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005450ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5451 if (!ObjCProtocolClassDecl) {
5452 ObjCProtocolClassDecl
5453 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5454 SourceLocation(),
5455 &Idents.get("Protocol"),
5456 /*PrevDecl=*/0,
5457 SourceLocation(), true);
5458 }
5459
5460 return ObjCProtocolClassDecl;
5461}
5462
Meador Ingec5613b22012-06-16 03:34:49 +00005463//===----------------------------------------------------------------------===//
5464// __builtin_va_list Construction Functions
5465//===----------------------------------------------------------------------===//
5466
5467static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5468 // typedef char* __builtin_va_list;
5469 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5470 TypeSourceInfo *TInfo
5471 = Context->getTrivialTypeSourceInfo(CharPtrType);
5472
5473 TypedefDecl *VaListTypeDecl
5474 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5475 Context->getTranslationUnitDecl(),
5476 SourceLocation(), SourceLocation(),
5477 &Context->Idents.get("__builtin_va_list"),
5478 TInfo);
5479 return VaListTypeDecl;
5480}
5481
5482static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5483 // typedef void* __builtin_va_list;
5484 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5485 TypeSourceInfo *TInfo
5486 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5487
5488 TypedefDecl *VaListTypeDecl
5489 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5490 Context->getTranslationUnitDecl(),
5491 SourceLocation(), SourceLocation(),
5492 &Context->Idents.get("__builtin_va_list"),
5493 TInfo);
5494 return VaListTypeDecl;
5495}
5496
5497static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5498 // typedef struct __va_list_tag {
5499 RecordDecl *VaListTagDecl;
5500
5501 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5502 Context->getTranslationUnitDecl(),
5503 &Context->Idents.get("__va_list_tag"));
5504 VaListTagDecl->startDefinition();
5505
5506 const size_t NumFields = 5;
5507 QualType FieldTypes[NumFields];
5508 const char *FieldNames[NumFields];
5509
5510 // unsigned char gpr;
5511 FieldTypes[0] = Context->UnsignedCharTy;
5512 FieldNames[0] = "gpr";
5513
5514 // unsigned char fpr;
5515 FieldTypes[1] = Context->UnsignedCharTy;
5516 FieldNames[1] = "fpr";
5517
5518 // unsigned short reserved;
5519 FieldTypes[2] = Context->UnsignedShortTy;
5520 FieldNames[2] = "reserved";
5521
5522 // void* overflow_arg_area;
5523 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5524 FieldNames[3] = "overflow_arg_area";
5525
5526 // void* reg_save_area;
5527 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5528 FieldNames[4] = "reg_save_area";
5529
5530 // Create fields
5531 for (unsigned i = 0; i < NumFields; ++i) {
5532 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5533 SourceLocation(),
5534 SourceLocation(),
5535 &Context->Idents.get(FieldNames[i]),
5536 FieldTypes[i], /*TInfo=*/0,
5537 /*BitWidth=*/0,
5538 /*Mutable=*/false,
5539 ICIS_NoInit);
5540 Field->setAccess(AS_public);
5541 VaListTagDecl->addDecl(Field);
5542 }
5543 VaListTagDecl->completeDefinition();
5544 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005545 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005546
5547 // } __va_list_tag;
5548 TypedefDecl *VaListTagTypedefDecl
5549 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5550 Context->getTranslationUnitDecl(),
5551 SourceLocation(), SourceLocation(),
5552 &Context->Idents.get("__va_list_tag"),
5553 Context->getTrivialTypeSourceInfo(VaListTagType));
5554 QualType VaListTagTypedefType =
5555 Context->getTypedefType(VaListTagTypedefDecl);
5556
5557 // typedef __va_list_tag __builtin_va_list[1];
5558 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5559 QualType VaListTagArrayType
5560 = Context->getConstantArrayType(VaListTagTypedefType,
5561 Size, ArrayType::Normal, 0);
5562 TypeSourceInfo *TInfo
5563 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5564 TypedefDecl *VaListTypedefDecl
5565 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5566 Context->getTranslationUnitDecl(),
5567 SourceLocation(), SourceLocation(),
5568 &Context->Idents.get("__builtin_va_list"),
5569 TInfo);
5570
5571 return VaListTypedefDecl;
5572}
5573
5574static TypedefDecl *
5575CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5576 // typedef struct __va_list_tag {
5577 RecordDecl *VaListTagDecl;
5578 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5579 Context->getTranslationUnitDecl(),
5580 &Context->Idents.get("__va_list_tag"));
5581 VaListTagDecl->startDefinition();
5582
5583 const size_t NumFields = 4;
5584 QualType FieldTypes[NumFields];
5585 const char *FieldNames[NumFields];
5586
5587 // unsigned gp_offset;
5588 FieldTypes[0] = Context->UnsignedIntTy;
5589 FieldNames[0] = "gp_offset";
5590
5591 // unsigned fp_offset;
5592 FieldTypes[1] = Context->UnsignedIntTy;
5593 FieldNames[1] = "fp_offset";
5594
5595 // void* overflow_arg_area;
5596 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5597 FieldNames[2] = "overflow_arg_area";
5598
5599 // void* reg_save_area;
5600 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5601 FieldNames[3] = "reg_save_area";
5602
5603 // Create fields
5604 for (unsigned i = 0; i < NumFields; ++i) {
5605 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5606 VaListTagDecl,
5607 SourceLocation(),
5608 SourceLocation(),
5609 &Context->Idents.get(FieldNames[i]),
5610 FieldTypes[i], /*TInfo=*/0,
5611 /*BitWidth=*/0,
5612 /*Mutable=*/false,
5613 ICIS_NoInit);
5614 Field->setAccess(AS_public);
5615 VaListTagDecl->addDecl(Field);
5616 }
5617 VaListTagDecl->completeDefinition();
5618 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005619 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005620
5621 // } __va_list_tag;
5622 TypedefDecl *VaListTagTypedefDecl
5623 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5624 Context->getTranslationUnitDecl(),
5625 SourceLocation(), SourceLocation(),
5626 &Context->Idents.get("__va_list_tag"),
5627 Context->getTrivialTypeSourceInfo(VaListTagType));
5628 QualType VaListTagTypedefType =
5629 Context->getTypedefType(VaListTagTypedefDecl);
5630
5631 // typedef __va_list_tag __builtin_va_list[1];
5632 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5633 QualType VaListTagArrayType
5634 = Context->getConstantArrayType(VaListTagTypedefType,
5635 Size, ArrayType::Normal,0);
5636 TypeSourceInfo *TInfo
5637 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5638 TypedefDecl *VaListTypedefDecl
5639 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5640 Context->getTranslationUnitDecl(),
5641 SourceLocation(), SourceLocation(),
5642 &Context->Idents.get("__builtin_va_list"),
5643 TInfo);
5644
5645 return VaListTypedefDecl;
5646}
5647
5648static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5649 // typedef int __builtin_va_list[4];
5650 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5651 QualType IntArrayType
5652 = Context->getConstantArrayType(Context->IntTy,
5653 Size, ArrayType::Normal, 0);
5654 TypedefDecl *VaListTypedefDecl
5655 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5656 Context->getTranslationUnitDecl(),
5657 SourceLocation(), SourceLocation(),
5658 &Context->Idents.get("__builtin_va_list"),
5659 Context->getTrivialTypeSourceInfo(IntArrayType));
5660
5661 return VaListTypedefDecl;
5662}
5663
Logan Chieneae5a8202012-10-10 06:56:20 +00005664static TypedefDecl *
5665CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5666 RecordDecl *VaListDecl;
5667 if (Context->getLangOpts().CPlusPlus) {
5668 // namespace std { struct __va_list {
5669 NamespaceDecl *NS;
5670 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5671 Context->getTranslationUnitDecl(),
5672 /*Inline*/false, SourceLocation(),
5673 SourceLocation(), &Context->Idents.get("std"),
5674 /*PrevDecl*/0);
5675
5676 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5677 Context->getTranslationUnitDecl(),
5678 SourceLocation(), SourceLocation(),
5679 &Context->Idents.get("__va_list"));
5680
5681 VaListDecl->setDeclContext(NS);
5682
5683 } else {
5684 // struct __va_list {
5685 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5686 Context->getTranslationUnitDecl(),
5687 &Context->Idents.get("__va_list"));
5688 }
5689
5690 VaListDecl->startDefinition();
5691
5692 // void * __ap;
5693 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5694 VaListDecl,
5695 SourceLocation(),
5696 SourceLocation(),
5697 &Context->Idents.get("__ap"),
5698 Context->getPointerType(Context->VoidTy),
5699 /*TInfo=*/0,
5700 /*BitWidth=*/0,
5701 /*Mutable=*/false,
5702 ICIS_NoInit);
5703 Field->setAccess(AS_public);
5704 VaListDecl->addDecl(Field);
5705
5706 // };
5707 VaListDecl->completeDefinition();
5708
5709 // typedef struct __va_list __builtin_va_list;
5710 TypeSourceInfo *TInfo
5711 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5712
5713 TypedefDecl *VaListTypeDecl
5714 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5715 Context->getTranslationUnitDecl(),
5716 SourceLocation(), SourceLocation(),
5717 &Context->Idents.get("__builtin_va_list"),
5718 TInfo);
5719
5720 return VaListTypeDecl;
5721}
5722
Meador Ingec5613b22012-06-16 03:34:49 +00005723static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5724 TargetInfo::BuiltinVaListKind Kind) {
5725 switch (Kind) {
5726 case TargetInfo::CharPtrBuiltinVaList:
5727 return CreateCharPtrBuiltinVaListDecl(Context);
5728 case TargetInfo::VoidPtrBuiltinVaList:
5729 return CreateVoidPtrBuiltinVaListDecl(Context);
5730 case TargetInfo::PowerABIBuiltinVaList:
5731 return CreatePowerABIBuiltinVaListDecl(Context);
5732 case TargetInfo::X86_64ABIBuiltinVaList:
5733 return CreateX86_64ABIBuiltinVaListDecl(Context);
5734 case TargetInfo::PNaClABIBuiltinVaList:
5735 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00005736 case TargetInfo::AAPCSABIBuiltinVaList:
5737 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005738 }
5739
5740 llvm_unreachable("Unhandled __builtin_va_list type kind");
5741}
5742
5743TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5744 if (!BuiltinVaListDecl)
5745 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5746
5747 return BuiltinVaListDecl;
5748}
5749
Meador Ingefb40e3f2012-07-01 15:57:25 +00005750QualType ASTContext::getVaListTagType() const {
5751 // Force the creation of VaListTagTy by building the __builtin_va_list
5752 // declaration.
5753 if (VaListTagTy.isNull())
5754 (void) getBuiltinVaListDecl();
5755
5756 return VaListTagTy;
5757}
5758
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005759void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005760 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005761 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005762
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005763 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005764}
5765
John McCall0bd6feb2009-12-02 08:04:21 +00005766/// \brief Retrieve the template name that corresponds to a non-empty
5767/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005768TemplateName
5769ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5770 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005771 unsigned size = End - Begin;
5772 assert(size > 1 && "set is not overloaded!");
5773
5774 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5775 size * sizeof(FunctionTemplateDecl*));
5776 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5777
5778 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005779 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005780 NamedDecl *D = *I;
5781 assert(isa<FunctionTemplateDecl>(D) ||
5782 (isa<UsingShadowDecl>(D) &&
5783 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5784 *Storage++ = D;
5785 }
5786
5787 return TemplateName(OT);
5788}
5789
Douglas Gregor7532dc62009-03-30 22:58:21 +00005790/// \brief Retrieve the template name that represents a qualified
5791/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005792TemplateName
5793ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5794 bool TemplateKeyword,
5795 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005796 assert(NNS && "Missing nested-name-specifier in qualified template name");
5797
Douglas Gregor789b1f62010-02-04 18:10:26 +00005798 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005799 llvm::FoldingSetNodeID ID;
5800 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5801
5802 void *InsertPos = 0;
5803 QualifiedTemplateName *QTN =
5804 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5805 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005806 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5807 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005808 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5809 }
5810
5811 return TemplateName(QTN);
5812}
5813
5814/// \brief Retrieve the template name that represents a dependent
5815/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005816TemplateName
5817ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5818 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005819 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005820 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005821
5822 llvm::FoldingSetNodeID ID;
5823 DependentTemplateName::Profile(ID, NNS, Name);
5824
5825 void *InsertPos = 0;
5826 DependentTemplateName *QTN =
5827 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5828
5829 if (QTN)
5830 return TemplateName(QTN);
5831
5832 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5833 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005834 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5835 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005836 } else {
5837 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00005838 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5839 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005840 DependentTemplateName *CheckQTN =
5841 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5842 assert(!CheckQTN && "Dependent type name canonicalization broken");
5843 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005844 }
5845
5846 DependentTemplateNames.InsertNode(QTN, InsertPos);
5847 return TemplateName(QTN);
5848}
5849
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005850/// \brief Retrieve the template name that represents a dependent
5851/// template name such as \c MetaFun::template operator+.
5852TemplateName
5853ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005854 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005855 assert((!NNS || NNS->isDependent()) &&
5856 "Nested name specifier must be dependent");
5857
5858 llvm::FoldingSetNodeID ID;
5859 DependentTemplateName::Profile(ID, NNS, Operator);
5860
5861 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005862 DependentTemplateName *QTN
5863 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005864
5865 if (QTN)
5866 return TemplateName(QTN);
5867
5868 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5869 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005870 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5871 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005872 } else {
5873 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00005874 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5875 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005876
5877 DependentTemplateName *CheckQTN
5878 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5879 assert(!CheckQTN && "Dependent template name canonicalization broken");
5880 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005881 }
5882
5883 DependentTemplateNames.InsertNode(QTN, InsertPos);
5884 return TemplateName(QTN);
5885}
5886
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005887TemplateName
John McCall14606042011-06-30 08:33:18 +00005888ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5889 TemplateName replacement) const {
5890 llvm::FoldingSetNodeID ID;
5891 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5892
5893 void *insertPos = 0;
5894 SubstTemplateTemplateParmStorage *subst
5895 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5896
5897 if (!subst) {
5898 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5899 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5900 }
5901
5902 return TemplateName(subst);
5903}
5904
5905TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005906ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5907 const TemplateArgument &ArgPack) const {
5908 ASTContext &Self = const_cast<ASTContext &>(*this);
5909 llvm::FoldingSetNodeID ID;
5910 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5911
5912 void *InsertPos = 0;
5913 SubstTemplateTemplateParmPackStorage *Subst
5914 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5915
5916 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005917 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005918 ArgPack.pack_size(),
5919 ArgPack.pack_begin());
5920 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5921 }
5922
5923 return TemplateName(Subst);
5924}
5925
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005926/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005927/// TargetInfo, produce the corresponding type. The unsigned @p Type
5928/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005929CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005930 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005931 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005932 case TargetInfo::SignedShort: return ShortTy;
5933 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5934 case TargetInfo::SignedInt: return IntTy;
5935 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5936 case TargetInfo::SignedLong: return LongTy;
5937 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5938 case TargetInfo::SignedLongLong: return LongLongTy;
5939 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5940 }
5941
David Blaikieb219cfc2011-09-23 05:06:16 +00005942 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005943}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005944
5945//===----------------------------------------------------------------------===//
5946// Type Predicates.
5947//===----------------------------------------------------------------------===//
5948
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005949/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5950/// garbage collection attribute.
5951///
John McCallae278a32011-01-12 00:34:59 +00005952Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005953 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005954 return Qualifiers::GCNone;
5955
David Blaikie4e4d0842012-03-11 07:00:24 +00005956 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005957 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5958
5959 // Default behaviour under objective-C's gc is for ObjC pointers
5960 // (or pointers to them) be treated as though they were declared
5961 // as __strong.
5962 if (GCAttrs == Qualifiers::GCNone) {
5963 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5964 return Qualifiers::Strong;
5965 else if (Ty->isPointerType())
5966 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5967 } else {
5968 // It's not valid to set GC attributes on anything that isn't a
5969 // pointer.
5970#ifndef NDEBUG
5971 QualType CT = Ty->getCanonicalTypeInternal();
5972 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5973 CT = AT->getElementType();
5974 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5975#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005976 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005977 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005978}
5979
Chris Lattner6ac46a42008-04-07 06:51:04 +00005980//===----------------------------------------------------------------------===//
5981// Type Compatibility Testing
5982//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005983
Mike Stump1eb44332009-09-09 15:08:12 +00005984/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005985/// compatible.
5986static bool areCompatVectorTypes(const VectorType *LHS,
5987 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005988 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005989 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005990 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005991}
5992
Douglas Gregor255210e2010-08-06 10:14:59 +00005993bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5994 QualType SecondVec) {
5995 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5996 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5997
5998 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5999 return true;
6000
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006001 // Treat Neon vector types and most AltiVec vector types as if they are the
6002 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006003 const VectorType *First = FirstVec->getAs<VectorType>();
6004 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006005 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006006 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006007 First->getVectorKind() != VectorType::AltiVecPixel &&
6008 First->getVectorKind() != VectorType::AltiVecBool &&
6009 Second->getVectorKind() != VectorType::AltiVecPixel &&
6010 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006011 return true;
6012
6013 return false;
6014}
6015
Steve Naroff4084c302009-07-23 01:01:38 +00006016//===----------------------------------------------------------------------===//
6017// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6018//===----------------------------------------------------------------------===//
6019
6020/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6021/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006022bool
6023ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6024 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006025 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006026 return true;
6027 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6028 E = rProto->protocol_end(); PI != E; ++PI)
6029 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6030 return true;
6031 return false;
6032}
6033
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006034/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006035/// return true if lhs's protocols conform to rhs's protocol; false
6036/// otherwise.
6037bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6038 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6039 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6040 return false;
6041}
6042
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006043/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6044/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006045bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6046 QualType rhs) {
6047 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6048 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6049 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6050
6051 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6052 E = lhsQID->qual_end(); I != E; ++I) {
6053 bool match = false;
6054 ObjCProtocolDecl *lhsProto = *I;
6055 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6056 E = rhsOPT->qual_end(); J != E; ++J) {
6057 ObjCProtocolDecl *rhsProto = *J;
6058 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6059 match = true;
6060 break;
6061 }
6062 }
6063 if (!match)
6064 return false;
6065 }
6066 return true;
6067}
6068
Steve Naroff4084c302009-07-23 01:01:38 +00006069/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6070/// ObjCQualifiedIDType.
6071bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6072 bool compare) {
6073 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006074 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006075 lhs->isObjCIdType() || lhs->isObjCClassType())
6076 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006077 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006078 rhs->isObjCIdType() || rhs->isObjCClassType())
6079 return true;
6080
6081 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006082 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006083
Steve Naroff4084c302009-07-23 01:01:38 +00006084 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006085
Steve Naroff4084c302009-07-23 01:01:38 +00006086 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006087 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006088 // make sure we check the class hierarchy.
6089 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6090 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6091 E = lhsQID->qual_end(); I != E; ++I) {
6092 // when comparing an id<P> on lhs with a static type on rhs,
6093 // see if static class implements all of id's protocols, directly or
6094 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006095 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006096 return false;
6097 }
6098 }
6099 // If there are no qualifiers and no interface, we have an 'id'.
6100 return true;
6101 }
Mike Stump1eb44332009-09-09 15:08:12 +00006102 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006103 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6104 E = lhsQID->qual_end(); I != E; ++I) {
6105 ObjCProtocolDecl *lhsProto = *I;
6106 bool match = false;
6107
6108 // when comparing an id<P> on lhs with a static type on rhs,
6109 // see if static class implements all of id's protocols, directly or
6110 // through its super class and categories.
6111 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6112 E = rhsOPT->qual_end(); J != E; ++J) {
6113 ObjCProtocolDecl *rhsProto = *J;
6114 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6115 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6116 match = true;
6117 break;
6118 }
6119 }
Mike Stump1eb44332009-09-09 15:08:12 +00006120 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006121 // make sure we check the class hierarchy.
6122 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6123 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6124 E = lhsQID->qual_end(); I != E; ++I) {
6125 // when comparing an id<P> on lhs with a static type on rhs,
6126 // see if static class implements all of id's protocols, directly or
6127 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006128 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006129 match = true;
6130 break;
6131 }
6132 }
6133 }
6134 if (!match)
6135 return false;
6136 }
Mike Stump1eb44332009-09-09 15:08:12 +00006137
Steve Naroff4084c302009-07-23 01:01:38 +00006138 return true;
6139 }
Mike Stump1eb44332009-09-09 15:08:12 +00006140
Steve Naroff4084c302009-07-23 01:01:38 +00006141 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6142 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6143
Mike Stump1eb44332009-09-09 15:08:12 +00006144 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006145 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006146 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006147 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6148 E = lhsOPT->qual_end(); I != E; ++I) {
6149 ObjCProtocolDecl *lhsProto = *I;
6150 bool match = false;
6151
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006152 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006153 // see if static class implements all of id's protocols, directly or
6154 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006155 // First, lhs protocols in the qualifier list must be found, direct
6156 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006157 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6158 E = rhsQID->qual_end(); J != E; ++J) {
6159 ObjCProtocolDecl *rhsProto = *J;
6160 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6161 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6162 match = true;
6163 break;
6164 }
6165 }
6166 if (!match)
6167 return false;
6168 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006169
6170 // Static class's protocols, or its super class or category protocols
6171 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6172 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6173 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6174 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6175 // This is rather dubious but matches gcc's behavior. If lhs has
6176 // no type qualifier and its class has no static protocol(s)
6177 // assume that it is mismatch.
6178 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6179 return false;
6180 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6181 LHSInheritedProtocols.begin(),
6182 E = LHSInheritedProtocols.end(); I != E; ++I) {
6183 bool match = false;
6184 ObjCProtocolDecl *lhsProto = (*I);
6185 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6186 E = rhsQID->qual_end(); J != E; ++J) {
6187 ObjCProtocolDecl *rhsProto = *J;
6188 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6189 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6190 match = true;
6191 break;
6192 }
6193 }
6194 if (!match)
6195 return false;
6196 }
6197 }
Steve Naroff4084c302009-07-23 01:01:38 +00006198 return true;
6199 }
6200 return false;
6201}
6202
Eli Friedman3d815e72008-08-22 00:56:42 +00006203/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006204/// compatible for assignment from RHS to LHS. This handles validation of any
6205/// protocol qualifiers on the LHS or RHS.
6206///
Steve Naroff14108da2009-07-10 23:34:53 +00006207bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6208 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006209 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6210 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6211
Steve Naroffde2e22d2009-07-15 18:40:39 +00006212 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006213 if (LHS->isObjCUnqualifiedIdOrClass() ||
6214 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006215 return true;
6216
John McCallc12c5bb2010-05-15 11:32:37 +00006217 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006218 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6219 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006220 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006221
6222 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6223 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6224 QualType(RHSOPT,0));
6225
John McCallc12c5bb2010-05-15 11:32:37 +00006226 // If we have 2 user-defined types, fall into that path.
6227 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006228 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006229
Steve Naroff4084c302009-07-23 01:01:38 +00006230 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006231}
6232
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006233/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006234/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006235/// arguments in block literals. When passed as arguments, passing 'A*' where
6236/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6237/// not OK. For the return type, the opposite is not OK.
6238bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6239 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006240 const ObjCObjectPointerType *RHSOPT,
6241 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006242 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006243 return true;
6244
6245 if (LHSOPT->isObjCBuiltinType()) {
6246 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6247 }
6248
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006249 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006250 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6251 QualType(RHSOPT,0),
6252 false);
6253
6254 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6255 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6256 if (LHS && RHS) { // We have 2 user-defined types.
6257 if (LHS != RHS) {
6258 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006259 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006260 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006261 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006262 }
6263 else
6264 return true;
6265 }
6266 return false;
6267}
6268
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006269/// getIntersectionOfProtocols - This routine finds the intersection of set
6270/// of protocols inherited from two distinct objective-c pointer objects.
6271/// It is used to build composite qualifier list of the composite type of
6272/// the conditional expression involving two objective-c pointer objects.
6273static
6274void getIntersectionOfProtocols(ASTContext &Context,
6275 const ObjCObjectPointerType *LHSOPT,
6276 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006277 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006278
John McCallc12c5bb2010-05-15 11:32:37 +00006279 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6280 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6281 assert(LHS->getInterface() && "LHS must have an interface base");
6282 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006283
6284 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6285 unsigned LHSNumProtocols = LHS->getNumProtocols();
6286 if (LHSNumProtocols > 0)
6287 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6288 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006289 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006290 Context.CollectInheritedProtocols(LHS->getInterface(),
6291 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006292 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6293 LHSInheritedProtocols.end());
6294 }
6295
6296 unsigned RHSNumProtocols = RHS->getNumProtocols();
6297 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006298 ObjCProtocolDecl **RHSProtocols =
6299 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006300 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6301 if (InheritedProtocolSet.count(RHSProtocols[i]))
6302 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006303 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006304 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006305 Context.CollectInheritedProtocols(RHS->getInterface(),
6306 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006307 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6308 RHSInheritedProtocols.begin(),
6309 E = RHSInheritedProtocols.end(); I != E; ++I)
6310 if (InheritedProtocolSet.count((*I)))
6311 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006312 }
6313}
6314
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006315/// areCommonBaseCompatible - Returns common base class of the two classes if
6316/// one found. Note that this is O'2 algorithm. But it will be called as the
6317/// last type comparison in a ?-exp of ObjC pointer types before a
6318/// warning is issued. So, its invokation is extremely rare.
6319QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006320 const ObjCObjectPointerType *Lptr,
6321 const ObjCObjectPointerType *Rptr) {
6322 const ObjCObjectType *LHS = Lptr->getObjectType();
6323 const ObjCObjectType *RHS = Rptr->getObjectType();
6324 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6325 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006326 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006327 return QualType();
6328
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006329 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006330 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006331 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006332 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006333 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6334
6335 QualType Result = QualType(LHS, 0);
6336 if (!Protocols.empty())
6337 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6338 Result = getObjCObjectPointerType(Result);
6339 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006340 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006341 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006342
6343 return QualType();
6344}
6345
John McCallc12c5bb2010-05-15 11:32:37 +00006346bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6347 const ObjCObjectType *RHS) {
6348 assert(LHS->getInterface() && "LHS is not an interface type");
6349 assert(RHS->getInterface() && "RHS is not an interface type");
6350
Chris Lattner6ac46a42008-04-07 06:51:04 +00006351 // Verify that the base decls are compatible: the RHS must be a subclass of
6352 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006353 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006354 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006355
Chris Lattner6ac46a42008-04-07 06:51:04 +00006356 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6357 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006358 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006359 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006360
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006361 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6362 // more detailed analysis is required.
6363 if (RHS->getNumProtocols() == 0) {
6364 // OK, if LHS is a superclass of RHS *and*
6365 // this superclass is assignment compatible with LHS.
6366 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006367 bool IsSuperClass =
6368 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6369 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006370 // OK if conversion of LHS to SuperClass results in narrowing of types
6371 // ; i.e., SuperClass may implement at least one of the protocols
6372 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6373 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6374 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006375 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006376 // If super class has no protocols, it is not a match.
6377 if (SuperClassInheritedProtocols.empty())
6378 return false;
6379
6380 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6381 LHSPE = LHS->qual_end();
6382 LHSPI != LHSPE; LHSPI++) {
6383 bool SuperImplementsProtocol = false;
6384 ObjCProtocolDecl *LHSProto = (*LHSPI);
6385
6386 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6387 SuperClassInheritedProtocols.begin(),
6388 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6389 ObjCProtocolDecl *SuperClassProto = (*I);
6390 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6391 SuperImplementsProtocol = true;
6392 break;
6393 }
6394 }
6395 if (!SuperImplementsProtocol)
6396 return false;
6397 }
6398 return true;
6399 }
6400 return false;
6401 }
Mike Stump1eb44332009-09-09 15:08:12 +00006402
John McCallc12c5bb2010-05-15 11:32:37 +00006403 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6404 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006405 LHSPI != LHSPE; LHSPI++) {
6406 bool RHSImplementsProtocol = false;
6407
6408 // If the RHS doesn't implement the protocol on the left, the types
6409 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006410 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6411 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006412 RHSPI != RHSPE; RHSPI++) {
6413 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006414 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006415 break;
6416 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006417 }
6418 // FIXME: For better diagnostics, consider passing back the protocol name.
6419 if (!RHSImplementsProtocol)
6420 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006421 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006422 // The RHS implements all protocols listed on the LHS.
6423 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006424}
6425
Steve Naroff389bf462009-02-12 17:52:19 +00006426bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6427 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006428 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6429 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006430
Steve Naroff14108da2009-07-10 23:34:53 +00006431 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006432 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006433
6434 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6435 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006436}
6437
Douglas Gregor569c3162010-08-07 11:51:51 +00006438bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6439 return canAssignObjCInterfaces(
6440 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6441 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6442}
6443
Mike Stump1eb44332009-09-09 15:08:12 +00006444/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006445/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006446/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006447/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006448bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6449 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006450 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006451 return hasSameType(LHS, RHS);
6452
Douglas Gregor447234d2010-07-29 15:18:02 +00006453 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006454}
6455
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006456bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006457 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006458}
6459
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006460bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6461 return !mergeTypes(LHS, RHS, true).isNull();
6462}
6463
Peter Collingbourne48466752010-10-24 18:30:18 +00006464/// mergeTransparentUnionType - if T is a transparent union type and a member
6465/// of T is compatible with SubType, return the merged type, else return
6466/// QualType()
6467QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6468 bool OfBlockPointer,
6469 bool Unqualified) {
6470 if (const RecordType *UT = T->getAsUnionType()) {
6471 RecordDecl *UD = UT->getDecl();
6472 if (UD->hasAttr<TransparentUnionAttr>()) {
6473 for (RecordDecl::field_iterator it = UD->field_begin(),
6474 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006475 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006476 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6477 if (!MT.isNull())
6478 return MT;
6479 }
6480 }
6481 }
6482
6483 return QualType();
6484}
6485
6486/// mergeFunctionArgumentTypes - merge two types which appear as function
6487/// argument types
6488QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6489 bool OfBlockPointer,
6490 bool Unqualified) {
6491 // GNU extension: two types are compatible if they appear as a function
6492 // argument, one of the types is a transparent union type and the other
6493 // type is compatible with a union member
6494 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6495 Unqualified);
6496 if (!lmerge.isNull())
6497 return lmerge;
6498
6499 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6500 Unqualified);
6501 if (!rmerge.isNull())
6502 return rmerge;
6503
6504 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6505}
6506
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006507QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006508 bool OfBlockPointer,
6509 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006510 const FunctionType *lbase = lhs->getAs<FunctionType>();
6511 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006512 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6513 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006514 bool allLTypes = true;
6515 bool allRTypes = true;
6516
6517 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006518 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006519 if (OfBlockPointer) {
6520 QualType RHS = rbase->getResultType();
6521 QualType LHS = lbase->getResultType();
6522 bool UnqualifiedResult = Unqualified;
6523 if (!UnqualifiedResult)
6524 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006525 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006526 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006527 else
John McCall8cc246c2010-12-15 01:06:38 +00006528 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6529 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006530 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006531
6532 if (Unqualified)
6533 retType = retType.getUnqualifiedType();
6534
6535 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6536 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6537 if (Unqualified) {
6538 LRetType = LRetType.getUnqualifiedType();
6539 RRetType = RRetType.getUnqualifiedType();
6540 }
6541
6542 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006543 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006544 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006545 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006546
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006547 // FIXME: double check this
6548 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6549 // rbase->getRegParmAttr() != 0 &&
6550 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006551 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6552 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006553
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006554 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006555 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006556 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006557
John McCall8cc246c2010-12-15 01:06:38 +00006558 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006559 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6560 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006561 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6562 return QualType();
6563
John McCallf85e1932011-06-15 23:02:42 +00006564 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6565 return QualType();
6566
John McCall8cc246c2010-12-15 01:06:38 +00006567 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6568 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006569
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006570 if (lbaseInfo.getNoReturn() != NoReturn)
6571 allLTypes = false;
6572 if (rbaseInfo.getNoReturn() != NoReturn)
6573 allRTypes = false;
6574
John McCallf85e1932011-06-15 23:02:42 +00006575 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006576
Eli Friedman3d815e72008-08-22 00:56:42 +00006577 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006578 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6579 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006580 unsigned lproto_nargs = lproto->getNumArgs();
6581 unsigned rproto_nargs = rproto->getNumArgs();
6582
6583 // Compatible functions must have the same number of arguments
6584 if (lproto_nargs != rproto_nargs)
6585 return QualType();
6586
6587 // Variadic and non-variadic functions aren't compatible
6588 if (lproto->isVariadic() != rproto->isVariadic())
6589 return QualType();
6590
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006591 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6592 return QualType();
6593
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006594 if (LangOpts.ObjCAutoRefCount &&
6595 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6596 return QualType();
6597
Eli Friedman3d815e72008-08-22 00:56:42 +00006598 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006599 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006600 for (unsigned i = 0; i < lproto_nargs; i++) {
6601 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6602 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006603 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6604 OfBlockPointer,
6605 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006606 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006607
6608 if (Unqualified)
6609 argtype = argtype.getUnqualifiedType();
6610
Eli Friedman3d815e72008-08-22 00:56:42 +00006611 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006612 if (Unqualified) {
6613 largtype = largtype.getUnqualifiedType();
6614 rargtype = rargtype.getUnqualifiedType();
6615 }
6616
Chris Lattner61710852008-10-05 17:34:18 +00006617 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6618 allLTypes = false;
6619 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6620 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006621 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006622
Eli Friedman3d815e72008-08-22 00:56:42 +00006623 if (allLTypes) return lhs;
6624 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006625
6626 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6627 EPI.ExtInfo = einfo;
6628 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006629 }
6630
6631 if (lproto) allRTypes = false;
6632 if (rproto) allLTypes = false;
6633
Douglas Gregor72564e72009-02-26 23:50:07 +00006634 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006635 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006636 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006637 if (proto->isVariadic()) return QualType();
6638 // Check that the types are compatible with the types that
6639 // would result from default argument promotions (C99 6.7.5.3p15).
6640 // The only types actually affected are promotable integer
6641 // types and floats, which would be passed as a different
6642 // type depending on whether the prototype is visible.
6643 unsigned proto_nargs = proto->getNumArgs();
6644 for (unsigned i = 0; i < proto_nargs; ++i) {
6645 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006646
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006647 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006648 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006649 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6650 argTy = Enum->getDecl()->getIntegerType();
6651 if (argTy.isNull())
6652 return QualType();
6653 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006654
Eli Friedman3d815e72008-08-22 00:56:42 +00006655 if (argTy->isPromotableIntegerType() ||
6656 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6657 return QualType();
6658 }
6659
6660 if (allLTypes) return lhs;
6661 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006662
6663 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6664 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006665 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006666 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006667 }
6668
6669 if (allLTypes) return lhs;
6670 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006671 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006672}
6673
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006674QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006675 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006676 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006677 // C++ [expr]: If an expression initially has the type "reference to T", the
6678 // type is adjusted to "T" prior to any further analysis, the expression
6679 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006680 // expression is an lvalue unless the reference is an rvalue reference and
6681 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006682 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6683 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006684
6685 if (Unqualified) {
6686 LHS = LHS.getUnqualifiedType();
6687 RHS = RHS.getUnqualifiedType();
6688 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006689
Eli Friedman3d815e72008-08-22 00:56:42 +00006690 QualType LHSCan = getCanonicalType(LHS),
6691 RHSCan = getCanonicalType(RHS);
6692
6693 // If two types are identical, they are compatible.
6694 if (LHSCan == RHSCan)
6695 return LHS;
6696
John McCall0953e762009-09-24 19:53:00 +00006697 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006698 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6699 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006700 if (LQuals != RQuals) {
6701 // If any of these qualifiers are different, we have a type
6702 // mismatch.
6703 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006704 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6705 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006706 return QualType();
6707
6708 // Exactly one GC qualifier difference is allowed: __strong is
6709 // okay if the other type has no GC qualifier but is an Objective
6710 // C object pointer (i.e. implicitly strong by default). We fix
6711 // this by pretending that the unqualified type was actually
6712 // qualified __strong.
6713 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6714 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6715 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6716
6717 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6718 return QualType();
6719
6720 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6721 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6722 }
6723 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6724 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6725 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006726 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006727 }
6728
6729 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006730
Eli Friedman852d63b2009-06-01 01:22:52 +00006731 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6732 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006733
Chris Lattner1adb8832008-01-14 05:45:46 +00006734 // We want to consider the two function types to be the same for these
6735 // comparisons, just force one to the other.
6736 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6737 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006738
6739 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006740 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6741 LHSClass = Type::ConstantArray;
6742 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6743 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006744
John McCallc12c5bb2010-05-15 11:32:37 +00006745 // ObjCInterfaces are just specialized ObjCObjects.
6746 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6747 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6748
Nate Begeman213541a2008-04-18 23:10:10 +00006749 // Canonicalize ExtVector -> Vector.
6750 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6751 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006752
Chris Lattnera36a61f2008-04-07 05:43:21 +00006753 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006754 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006755 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006756 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006757 // Compatibility is based on the underlying type, not the promotion
6758 // type.
John McCall183700f2009-09-21 23:43:11 +00006759 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006760 QualType TINT = ETy->getDecl()->getIntegerType();
6761 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006762 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006763 }
John McCall183700f2009-09-21 23:43:11 +00006764 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006765 QualType TINT = ETy->getDecl()->getIntegerType();
6766 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006767 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006768 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006769 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006770 if (OfBlockPointer && !BlockReturnType) {
6771 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6772 return LHS;
6773 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6774 return RHS;
6775 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006776
Eli Friedman3d815e72008-08-22 00:56:42 +00006777 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006778 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006779
Steve Naroff4a746782008-01-09 22:43:08 +00006780 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006781 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006782#define TYPE(Class, Base)
6783#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006784#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006785#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6786#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6787#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006788 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006789
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006790 case Type::LValueReference:
6791 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006792 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006793 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006794
John McCallc12c5bb2010-05-15 11:32:37 +00006795 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006796 case Type::IncompleteArray:
6797 case Type::VariableArray:
6798 case Type::FunctionProto:
6799 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006800 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006801
Chris Lattner1adb8832008-01-14 05:45:46 +00006802 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006803 {
6804 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006805 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6806 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006807 if (Unqualified) {
6808 LHSPointee = LHSPointee.getUnqualifiedType();
6809 RHSPointee = RHSPointee.getUnqualifiedType();
6810 }
6811 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6812 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006813 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006814 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006815 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006816 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006817 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006818 return getPointerType(ResultType);
6819 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006820 case Type::BlockPointer:
6821 {
6822 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006823 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6824 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006825 if (Unqualified) {
6826 LHSPointee = LHSPointee.getUnqualifiedType();
6827 RHSPointee = RHSPointee.getUnqualifiedType();
6828 }
6829 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6830 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006831 if (ResultType.isNull()) return QualType();
6832 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6833 return LHS;
6834 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6835 return RHS;
6836 return getBlockPointerType(ResultType);
6837 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006838 case Type::Atomic:
6839 {
6840 // Merge two pointer types, while trying to preserve typedef info
6841 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6842 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6843 if (Unqualified) {
6844 LHSValue = LHSValue.getUnqualifiedType();
6845 RHSValue = RHSValue.getUnqualifiedType();
6846 }
6847 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6848 Unqualified);
6849 if (ResultType.isNull()) return QualType();
6850 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6851 return LHS;
6852 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6853 return RHS;
6854 return getAtomicType(ResultType);
6855 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006856 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006857 {
6858 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6859 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6860 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6861 return QualType();
6862
6863 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6864 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006865 if (Unqualified) {
6866 LHSElem = LHSElem.getUnqualifiedType();
6867 RHSElem = RHSElem.getUnqualifiedType();
6868 }
6869
6870 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006871 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006872 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6873 return LHS;
6874 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6875 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006876 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6877 ArrayType::ArraySizeModifier(), 0);
6878 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6879 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006880 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6881 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006882 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6883 return LHS;
6884 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6885 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006886 if (LVAT) {
6887 // FIXME: This isn't correct! But tricky to implement because
6888 // the array's size has to be the size of LHS, but the type
6889 // has to be different.
6890 return LHS;
6891 }
6892 if (RVAT) {
6893 // FIXME: This isn't correct! But tricky to implement because
6894 // the array's size has to be the size of RHS, but the type
6895 // has to be different.
6896 return RHS;
6897 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006898 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6899 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006900 return getIncompleteArrayType(ResultType,
6901 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006902 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006903 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006904 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006905 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006906 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006907 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006908 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006909 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006910 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006911 case Type::Complex:
6912 // Distinct complex types are incompatible.
6913 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006914 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006915 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006916 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6917 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006918 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006919 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006920 case Type::ObjCObject: {
6921 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006922 // FIXME: This should be type compatibility, e.g. whether
6923 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006924 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6925 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6926 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006927 return LHS;
6928
Eli Friedman3d815e72008-08-22 00:56:42 +00006929 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006930 }
Steve Naroff14108da2009-07-10 23:34:53 +00006931 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006932 if (OfBlockPointer) {
6933 if (canAssignObjCInterfacesInBlockPointer(
6934 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006935 RHS->getAs<ObjCObjectPointerType>(),
6936 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006937 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006938 return QualType();
6939 }
John McCall183700f2009-09-21 23:43:11 +00006940 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6941 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006942 return LHS;
6943
Steve Naroffbc76dd02008-12-10 22:14:21 +00006944 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006945 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006946 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006947
David Blaikie7530c032012-01-17 06:56:22 +00006948 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006949}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006950
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006951bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6952 const FunctionProtoType *FromFunctionType,
6953 const FunctionProtoType *ToFunctionType) {
6954 if (FromFunctionType->hasAnyConsumedArgs() !=
6955 ToFunctionType->hasAnyConsumedArgs())
6956 return false;
6957 FunctionProtoType::ExtProtoInfo FromEPI =
6958 FromFunctionType->getExtProtoInfo();
6959 FunctionProtoType::ExtProtoInfo ToEPI =
6960 ToFunctionType->getExtProtoInfo();
6961 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6962 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6963 ArgIdx != NumArgs; ++ArgIdx) {
6964 if (FromEPI.ConsumedArguments[ArgIdx] !=
6965 ToEPI.ConsumedArguments[ArgIdx])
6966 return false;
6967 }
6968 return true;
6969}
6970
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006971/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6972/// 'RHS' attributes and returns the merged version; including for function
6973/// return types.
6974QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6975 QualType LHSCan = getCanonicalType(LHS),
6976 RHSCan = getCanonicalType(RHS);
6977 // If two types are identical, they are compatible.
6978 if (LHSCan == RHSCan)
6979 return LHS;
6980 if (RHSCan->isFunctionType()) {
6981 if (!LHSCan->isFunctionType())
6982 return QualType();
6983 QualType OldReturnType =
6984 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6985 QualType NewReturnType =
6986 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6987 QualType ResReturnType =
6988 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6989 if (ResReturnType.isNull())
6990 return QualType();
6991 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6992 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6993 // In either case, use OldReturnType to build the new function type.
6994 const FunctionType *F = LHS->getAs<FunctionType>();
6995 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006996 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6997 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006998 QualType ResultType
6999 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00007000 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007001 return ResultType;
7002 }
7003 }
7004 return QualType();
7005 }
7006
7007 // If the qualifiers are different, the types can still be merged.
7008 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7009 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7010 if (LQuals != RQuals) {
7011 // If any of these qualifiers are different, we have a type mismatch.
7012 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7013 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7014 return QualType();
7015
7016 // Exactly one GC qualifier difference is allowed: __strong is
7017 // okay if the other type has no GC qualifier but is an Objective
7018 // C object pointer (i.e. implicitly strong by default). We fix
7019 // this by pretending that the unqualified type was actually
7020 // qualified __strong.
7021 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7022 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7023 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7024
7025 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7026 return QualType();
7027
7028 if (GC_L == Qualifiers::Strong)
7029 return LHS;
7030 if (GC_R == Qualifiers::Strong)
7031 return RHS;
7032 return QualType();
7033 }
7034
7035 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7036 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7037 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7038 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7039 if (ResQT == LHSBaseQT)
7040 return LHS;
7041 if (ResQT == RHSBaseQT)
7042 return RHS;
7043 }
7044 return QualType();
7045}
7046
Chris Lattner5426bf62008-04-07 07:01:58 +00007047//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007048// Integer Predicates
7049//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007050
Jay Foad4ba2a172011-01-12 09:06:06 +00007051unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007052 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007053 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007054 if (T->isBooleanType())
7055 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007056 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007057 return (unsigned)getTypeSize(T);
7058}
7059
Abramo Bagnara762f1592012-09-09 10:21:24 +00007060QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007061 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007062
7063 // Turn <4 x signed int> -> <4 x unsigned int>
7064 if (const VectorType *VTy = T->getAs<VectorType>())
7065 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007066 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007067
7068 // For enums, we return the unsigned version of the base type.
7069 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007070 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007071
7072 const BuiltinType *BTy = T->getAs<BuiltinType>();
7073 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007074 switch (BTy->getKind()) {
7075 case BuiltinType::Char_S:
7076 case BuiltinType::SChar:
7077 return UnsignedCharTy;
7078 case BuiltinType::Short:
7079 return UnsignedShortTy;
7080 case BuiltinType::Int:
7081 return UnsignedIntTy;
7082 case BuiltinType::Long:
7083 return UnsignedLongTy;
7084 case BuiltinType::LongLong:
7085 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007086 case BuiltinType::Int128:
7087 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007088 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007089 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007090 }
7091}
7092
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007093ASTMutationListener::~ASTMutationListener() { }
7094
Chris Lattner86df27b2009-06-14 00:45:47 +00007095
7096//===----------------------------------------------------------------------===//
7097// Builtin Type Computation
7098//===----------------------------------------------------------------------===//
7099
7100/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007101/// pointer over the consumed characters. This returns the resultant type. If
7102/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7103/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7104/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007105///
7106/// RequiresICE is filled in on return to indicate whether the value is required
7107/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007108static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007109 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007110 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007111 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007112 // Modifiers.
7113 int HowLong = 0;
7114 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007115 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007116
Chris Lattner33daae62010-10-01 22:42:38 +00007117 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007118 bool Done = false;
7119 while (!Done) {
7120 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007121 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007122 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007123 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007124 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007125 case 'S':
7126 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7127 assert(!Signed && "Can't use 'S' modifier multiple times!");
7128 Signed = true;
7129 break;
7130 case 'U':
7131 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7132 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7133 Unsigned = true;
7134 break;
7135 case 'L':
7136 assert(HowLong <= 2 && "Can't have LLLL modifier");
7137 ++HowLong;
7138 break;
7139 }
7140 }
7141
7142 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007143
Chris Lattner86df27b2009-06-14 00:45:47 +00007144 // Read the base type.
7145 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007146 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007147 case 'v':
7148 assert(HowLong == 0 && !Signed && !Unsigned &&
7149 "Bad modifiers used with 'v'!");
7150 Type = Context.VoidTy;
7151 break;
7152 case 'f':
7153 assert(HowLong == 0 && !Signed && !Unsigned &&
7154 "Bad modifiers used with 'f'!");
7155 Type = Context.FloatTy;
7156 break;
7157 case 'd':
7158 assert(HowLong < 2 && !Signed && !Unsigned &&
7159 "Bad modifiers used with 'd'!");
7160 if (HowLong)
7161 Type = Context.LongDoubleTy;
7162 else
7163 Type = Context.DoubleTy;
7164 break;
7165 case 's':
7166 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7167 if (Unsigned)
7168 Type = Context.UnsignedShortTy;
7169 else
7170 Type = Context.ShortTy;
7171 break;
7172 case 'i':
7173 if (HowLong == 3)
7174 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7175 else if (HowLong == 2)
7176 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7177 else if (HowLong == 1)
7178 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7179 else
7180 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7181 break;
7182 case 'c':
7183 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7184 if (Signed)
7185 Type = Context.SignedCharTy;
7186 else if (Unsigned)
7187 Type = Context.UnsignedCharTy;
7188 else
7189 Type = Context.CharTy;
7190 break;
7191 case 'b': // boolean
7192 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7193 Type = Context.BoolTy;
7194 break;
7195 case 'z': // size_t.
7196 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7197 Type = Context.getSizeType();
7198 break;
7199 case 'F':
7200 Type = Context.getCFConstantStringType();
7201 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007202 case 'G':
7203 Type = Context.getObjCIdType();
7204 break;
7205 case 'H':
7206 Type = Context.getObjCSelType();
7207 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007208 case 'a':
7209 Type = Context.getBuiltinVaListType();
7210 assert(!Type.isNull() && "builtin va list type not initialized!");
7211 break;
7212 case 'A':
7213 // This is a "reference" to a va_list; however, what exactly
7214 // this means depends on how va_list is defined. There are two
7215 // different kinds of va_list: ones passed by value, and ones
7216 // passed by reference. An example of a by-value va_list is
7217 // x86, where va_list is a char*. An example of by-ref va_list
7218 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7219 // we want this argument to be a char*&; for x86-64, we want
7220 // it to be a __va_list_tag*.
7221 Type = Context.getBuiltinVaListType();
7222 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007223 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007224 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007225 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007226 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007227 break;
7228 case 'V': {
7229 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007230 unsigned NumElements = strtoul(Str, &End, 10);
7231 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007232 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007233
Chris Lattner14e0e742010-10-01 22:53:11 +00007234 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7235 RequiresICE, false);
7236 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007237
7238 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007239 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007240 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007241 break;
7242 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007243 case 'E': {
7244 char *End;
7245
7246 unsigned NumElements = strtoul(Str, &End, 10);
7247 assert(End != Str && "Missing vector size");
7248
7249 Str = End;
7250
7251 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7252 false);
7253 Type = Context.getExtVectorType(ElementType, NumElements);
7254 break;
7255 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007256 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007257 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7258 false);
7259 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007260 Type = Context.getComplexType(ElementType);
7261 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007262 }
7263 case 'Y' : {
7264 Type = Context.getPointerDiffType();
7265 break;
7266 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007267 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007268 Type = Context.getFILEType();
7269 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007270 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007271 return QualType();
7272 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007273 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007274 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007275 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007276 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007277 else
7278 Type = Context.getjmp_bufType();
7279
Mike Stumpfd612db2009-07-28 23:47:15 +00007280 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007281 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007282 return QualType();
7283 }
7284 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007285 case 'K':
7286 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7287 Type = Context.getucontext_tType();
7288
7289 if (Type.isNull()) {
7290 Error = ASTContext::GE_Missing_ucontext;
7291 return QualType();
7292 }
7293 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007294 case 'p':
7295 Type = Context.getProcessIDType();
7296 break;
Mike Stump782fa302009-07-28 02:25:19 +00007297 }
Mike Stump1eb44332009-09-09 15:08:12 +00007298
Chris Lattner33daae62010-10-01 22:42:38 +00007299 // If there are modifiers and if we're allowed to parse them, go for it.
7300 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007301 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007302 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007303 default: Done = true; --Str; break;
7304 case '*':
7305 case '&': {
7306 // Both pointers and references can have their pointee types
7307 // qualified with an address space.
7308 char *End;
7309 unsigned AddrSpace = strtoul(Str, &End, 10);
7310 if (End != Str && AddrSpace != 0) {
7311 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7312 Str = End;
7313 }
7314 if (c == '*')
7315 Type = Context.getPointerType(Type);
7316 else
7317 Type = Context.getLValueReferenceType(Type);
7318 break;
7319 }
7320 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7321 case 'C':
7322 Type = Type.withConst();
7323 break;
7324 case 'D':
7325 Type = Context.getVolatileType(Type);
7326 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007327 case 'R':
7328 Type = Type.withRestrict();
7329 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007330 }
7331 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007332
Chris Lattner14e0e742010-10-01 22:53:11 +00007333 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007334 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007335
Chris Lattner86df27b2009-06-14 00:45:47 +00007336 return Type;
7337}
7338
7339/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007340QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007341 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007342 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007343 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007344
Chris Lattner5f9e2722011-07-23 10:55:15 +00007345 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007346
Chris Lattner14e0e742010-10-01 22:53:11 +00007347 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007348 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007349 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7350 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007351 if (Error != GE_None)
7352 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007353
7354 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7355
Chris Lattner86df27b2009-06-14 00:45:47 +00007356 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007357 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007358 if (Error != GE_None)
7359 return QualType();
7360
Chris Lattner14e0e742010-10-01 22:53:11 +00007361 // If this argument is required to be an IntegerConstantExpression and the
7362 // caller cares, fill in the bitmask we return.
7363 if (RequiresICE && IntegerConstantArgs)
7364 *IntegerConstantArgs |= 1 << ArgTypes.size();
7365
Chris Lattner86df27b2009-06-14 00:45:47 +00007366 // Do array -> pointer decay. The builtin should use the decayed type.
7367 if (Ty->isArrayType())
7368 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007369
Chris Lattner86df27b2009-06-14 00:45:47 +00007370 ArgTypes.push_back(Ty);
7371 }
7372
7373 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7374 "'.' should only occur at end of builtin type list!");
7375
John McCall00ccbef2010-12-21 00:44:39 +00007376 FunctionType::ExtInfo EI;
7377 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7378
7379 bool Variadic = (TypeStr[0] == '.');
7380
7381 // We really shouldn't be making a no-proto type here, especially in C++.
7382 if (ArgTypes.empty() && Variadic)
7383 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007384
John McCalle23cf432010-12-14 08:05:40 +00007385 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007386 EPI.ExtInfo = EI;
7387 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007388
7389 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007390}
Eli Friedmana95d7572009-08-19 07:44:53 +00007391
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007392GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7393 GVALinkage External = GVA_StrongExternal;
7394
7395 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007396 switch (L) {
7397 case NoLinkage:
7398 case InternalLinkage:
7399 case UniqueExternalLinkage:
7400 return GVA_Internal;
7401
7402 case ExternalLinkage:
7403 switch (FD->getTemplateSpecializationKind()) {
7404 case TSK_Undeclared:
7405 case TSK_ExplicitSpecialization:
7406 External = GVA_StrongExternal;
7407 break;
7408
7409 case TSK_ExplicitInstantiationDefinition:
7410 return GVA_ExplicitTemplateInstantiation;
7411
7412 case TSK_ExplicitInstantiationDeclaration:
7413 case TSK_ImplicitInstantiation:
7414 External = GVA_TemplateInstantiation;
7415 break;
7416 }
7417 }
7418
7419 if (!FD->isInlined())
7420 return External;
7421
David Blaikie4e4d0842012-03-11 07:00:24 +00007422 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007423 // GNU or C99 inline semantics. Determine whether this symbol should be
7424 // externally visible.
7425 if (FD->isInlineDefinitionExternallyVisible())
7426 return External;
7427
7428 // C99 inline semantics, where the symbol is not externally visible.
7429 return GVA_C99Inline;
7430 }
7431
7432 // C++0x [temp.explicit]p9:
7433 // [ Note: The intent is that an inline function that is the subject of
7434 // an explicit instantiation declaration will still be implicitly
7435 // instantiated when used so that the body can be considered for
7436 // inlining, but that no out-of-line copy of the inline function would be
7437 // generated in the translation unit. -- end note ]
7438 if (FD->getTemplateSpecializationKind()
7439 == TSK_ExplicitInstantiationDeclaration)
7440 return GVA_C99Inline;
7441
7442 return GVA_CXXInline;
7443}
7444
7445GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7446 // If this is a static data member, compute the kind of template
7447 // specialization. Otherwise, this variable is not part of a
7448 // template.
7449 TemplateSpecializationKind TSK = TSK_Undeclared;
7450 if (VD->isStaticDataMember())
7451 TSK = VD->getTemplateSpecializationKind();
7452
7453 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00007454 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007455 VD->getType()->getLinkage() == UniqueExternalLinkage)
7456 L = UniqueExternalLinkage;
7457
7458 switch (L) {
7459 case NoLinkage:
7460 case InternalLinkage:
7461 case UniqueExternalLinkage:
7462 return GVA_Internal;
7463
7464 case ExternalLinkage:
7465 switch (TSK) {
7466 case TSK_Undeclared:
7467 case TSK_ExplicitSpecialization:
7468 return GVA_StrongExternal;
7469
7470 case TSK_ExplicitInstantiationDeclaration:
7471 llvm_unreachable("Variable should not be instantiated");
7472 // Fall through to treat this like any other instantiation.
7473
7474 case TSK_ExplicitInstantiationDefinition:
7475 return GVA_ExplicitTemplateInstantiation;
7476
7477 case TSK_ImplicitInstantiation:
7478 return GVA_TemplateInstantiation;
7479 }
7480 }
7481
David Blaikie7530c032012-01-17 06:56:22 +00007482 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007483}
7484
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007485bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007486 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7487 if (!VD->isFileVarDecl())
7488 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007489 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007490 return false;
7491
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007492 // Weak references don't produce any output by themselves.
7493 if (D->hasAttr<WeakRefAttr>())
7494 return false;
7495
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007496 // Aliases and used decls are required.
7497 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7498 return true;
7499
7500 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7501 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007502 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007503 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007504
7505 // Constructors and destructors are required.
7506 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7507 return true;
7508
7509 // The key function for a class is required.
7510 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7511 const CXXRecordDecl *RD = MD->getParent();
7512 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7513 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7514 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7515 return true;
7516 }
7517 }
7518
7519 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7520
7521 // static, static inline, always_inline, and extern inline functions can
7522 // always be deferred. Normal inline functions can be deferred in C99/C++.
7523 // Implicit template instantiations can also be deferred in C++.
7524 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007525 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007526 return false;
7527 return true;
7528 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007529
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007530 const VarDecl *VD = cast<VarDecl>(D);
7531 assert(VD->isFileVarDecl() && "Expected file scoped var");
7532
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007533 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7534 return false;
7535
Richard Smith5f9a7e32012-11-12 21:38:00 +00007536 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007537 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007538 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7539 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007540
Richard Smith5f9a7e32012-11-12 21:38:00 +00007541 // Variables that have destruction with side-effects are required.
7542 if (VD->getType().isDestructedType())
7543 return true;
7544
7545 // Variables that have initialization with side-effects are required.
7546 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7547 return true;
7548
7549 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007550}
Charles Davis071cc7d2010-08-16 03:33:14 +00007551
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007552CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007553 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007554 return ABI->getDefaultMethodCallConv(isVariadic);
7555}
7556
7557CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7558 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7559 return CC_Default;
7560 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007561}
7562
Jay Foad4ba2a172011-01-12 09:06:06 +00007563bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007564 // Pass through to the C++ ABI object
7565 return ABI->isNearlyEmpty(RD);
7566}
7567
Peter Collingbourne14110472011-01-13 18:57:25 +00007568MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007569 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007570 case CXXABI_ARM:
7571 case CXXABI_Itanium:
7572 return createItaniumMangleContext(*this, getDiagnostics());
7573 case CXXABI_Microsoft:
7574 return createMicrosoftMangleContext(*this, getDiagnostics());
7575 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007576 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007577}
7578
Charles Davis071cc7d2010-08-16 03:33:14 +00007579CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007580
7581size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007582 return ASTRecordLayouts.getMemorySize()
7583 + llvm::capacity_in_bytes(ObjCLayouts)
7584 + llvm::capacity_in_bytes(KeyFunctions)
7585 + llvm::capacity_in_bytes(ObjCImpls)
7586 + llvm::capacity_in_bytes(BlockVarCopyInits)
7587 + llvm::capacity_in_bytes(DeclAttrs)
7588 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7589 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7590 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7591 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7592 + llvm::capacity_in_bytes(OverriddenMethods)
7593 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007594 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007595 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007596}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007597
David Blaikie66cff722012-11-14 01:52:05 +00007598void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7599 // FIXME: This mangling should be applied to function local classes too
7600 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7601 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7602 return;
7603
7604 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7605 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7606 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7607}
7608
7609int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7610 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7611 UnnamedMangleNumbers.find(Tag);
7612 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7613}
7614
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007615unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7616 CXXRecordDecl *Lambda = CallOperator->getParent();
7617 return LambdaMangleContexts[Lambda->getDeclContext()]
7618 .getManglingNumber(CallOperator);
7619}
7620
7621
Ted Kremenekd211cb72011-10-06 05:00:56 +00007622void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7623 ParamIndices[D] = index;
7624}
7625
7626unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7627 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7628 assert(I != ParamIndices.end() &&
7629 "ParmIndices lacks entry set by ParmVarDecl");
7630 return I->second;
7631}