blob: 83e6d6bd286d195bb1a7024fe519b5e5bb73eb2b [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 Jahanianc328d9c2013-01-12 00:28:34 +0000416 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
417 if (OMD && OMD->isPropertyAccessor()) {
418 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) {
419 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) {
420 comments::FullComment *CFC = cloneFullComment(FC, D);
421 return CFC;
422 }
423 }
424 }
425 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000426 addRedeclaredMethods(OMD, Overridden);
427 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
428 for (unsigned i = 0, e = Overridden.size(); i < e; i++) {
429 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000430 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000431 return CFC;
432 }
433 }
434 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000435 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000436 }
437
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000438 // If the RawComment was attached to other redeclaration of this Decl, we
439 // should parse the comment in context of that other Decl. This is important
440 // because comments can contain references to parameter names which can be
441 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000442 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000443 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000444
Dmitri Gribenko19523542012-09-29 11:40:46 +0000445 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000446 ParsedComments[Canonical] = FC;
447 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000448}
449
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000450void
451ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
452 TemplateTemplateParmDecl *Parm) {
453 ID.AddInteger(Parm->getDepth());
454 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000455 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000456
457 TemplateParameterList *Params = Parm->getTemplateParameters();
458 ID.AddInteger(Params->size());
459 for (TemplateParameterList::const_iterator P = Params->begin(),
460 PEnd = Params->end();
461 P != PEnd; ++P) {
462 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
463 ID.AddInteger(0);
464 ID.AddBoolean(TTP->isParameterPack());
465 continue;
466 }
467
468 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
469 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000470 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000471 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000472 if (NTTP->isExpandedParameterPack()) {
473 ID.AddBoolean(true);
474 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000475 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
476 QualType T = NTTP->getExpansionType(I);
477 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
478 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000479 } else
480 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000481 continue;
482 }
483
484 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
485 ID.AddInteger(2);
486 Profile(ID, TTP);
487 }
488}
489
490TemplateTemplateParmDecl *
491ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000492 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000493 // Check if we already have a canonical template template parameter.
494 llvm::FoldingSetNodeID ID;
495 CanonicalTemplateTemplateParm::Profile(ID, TTP);
496 void *InsertPos = 0;
497 CanonicalTemplateTemplateParm *Canonical
498 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
499 if (Canonical)
500 return Canonical->getParam();
501
502 // Build a canonical template parameter list.
503 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000504 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000505 CanonParams.reserve(Params->size());
506 for (TemplateParameterList::const_iterator P = Params->begin(),
507 PEnd = Params->end();
508 P != PEnd; ++P) {
509 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
510 CanonParams.push_back(
511 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000512 SourceLocation(),
513 SourceLocation(),
514 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000515 TTP->getIndex(), 0, false,
516 TTP->isParameterPack()));
517 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000518 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
519 QualType T = getCanonicalType(NTTP->getType());
520 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
521 NonTypeTemplateParmDecl *Param;
522 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000523 SmallVector<QualType, 2> ExpandedTypes;
524 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000525 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
526 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
527 ExpandedTInfos.push_back(
528 getTrivialTypeSourceInfo(ExpandedTypes.back()));
529 }
530
531 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000532 SourceLocation(),
533 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000534 NTTP->getDepth(),
535 NTTP->getPosition(), 0,
536 T,
537 TInfo,
538 ExpandedTypes.data(),
539 ExpandedTypes.size(),
540 ExpandedTInfos.data());
541 } else {
542 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000543 SourceLocation(),
544 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000545 NTTP->getDepth(),
546 NTTP->getPosition(), 0,
547 T,
548 NTTP->isParameterPack(),
549 TInfo);
550 }
551 CanonParams.push_back(Param);
552
553 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000554 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
555 cast<TemplateTemplateParmDecl>(*P)));
556 }
557
558 TemplateTemplateParmDecl *CanonTTP
559 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
560 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000561 TTP->getPosition(),
562 TTP->isParameterPack(),
563 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000564 TemplateParameterList::Create(*this, SourceLocation(),
565 SourceLocation(),
566 CanonParams.data(),
567 CanonParams.size(),
568 SourceLocation()));
569
570 // Get the new insert position for the node we care about.
571 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
572 assert(Canonical == 0 && "Shouldn't be in the map!");
573 (void)Canonical;
574
575 // Create the canonical template template parameter entry.
576 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
577 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
578 return CanonTTP;
579}
580
Charles Davis071cc7d2010-08-16 03:33:14 +0000581CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000582 if (!LangOpts.CPlusPlus) return 0;
583
Charles Davis20cf7172010-08-19 02:18:14 +0000584 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000585 case CXXABI_ARM:
586 return CreateARMCXXABI(*this);
587 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000588 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000589 case CXXABI_Microsoft:
590 return CreateMicrosoftCXXABI(*this);
591 }
David Blaikie7530c032012-01-17 06:56:22 +0000592 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000593}
594
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000595static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000596 const LangOptions &LOpts) {
597 if (LOpts.FakeAddressSpaceMap) {
598 // The fake address space map must have a distinct entry for each
599 // language-specific address space.
600 static const unsigned FakeAddrSpaceMap[] = {
601 1, // opencl_global
602 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000603 3, // opencl_constant
604 4, // cuda_device
605 5, // cuda_constant
606 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000607 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000608 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000609 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000610 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000611 }
612}
613
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000614ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000615 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000616 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000617 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000618 unsigned size_reserve,
619 bool DelayInitialization)
620 : FunctionProtoTypes(this_()),
621 TemplateSpecializationTypes(this_()),
622 DependentTemplateSpecializationTypes(this_()),
623 SubstTemplateTemplateParmPacks(this_()),
624 GlobalNestedNameSpecifier(0),
625 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000626 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000627 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000628 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000629 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000630 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000631 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
632 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
633 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000634 NullTypeSourceInfo(QualType()),
635 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000636 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000637 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000638 Idents(idents), Selectors(sels),
639 BuiltinInfo(builtins),
640 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000641 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000642 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000643 CommentCommandTraits(BumpAlloc),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000644 LastSDM(0, 0),
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000645 UniqueBlockByRefTypeID(0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000646{
Mike Stump1eb44332009-09-09 15:08:12 +0000647 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000648 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000649
650 if (!DelayInitialization) {
651 assert(t && "No target supplied for ASTContext initialization");
652 InitBuiltinTypes(*t);
653 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000654}
655
Reid Spencer5f016e22007-07-11 17:01:13 +0000656ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000657 // Release the DenseMaps associated with DeclContext objects.
658 // FIXME: Is this the ideal solution?
659 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000660
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000661 // Call all of the deallocation functions.
662 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
663 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000664
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000665 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000666 // because they can contain DenseMaps.
667 for (llvm::DenseMap<const ObjCContainerDecl*,
668 const ASTRecordLayout*>::iterator
669 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
670 // Increment in loop to prevent using deallocated memory.
671 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
672 R->Destroy(*this);
673
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000674 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
675 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
676 // Increment in loop to prevent using deallocated memory.
677 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
678 R->Destroy(*this);
679 }
Douglas Gregor63200642010-08-30 16:49:28 +0000680
681 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
682 AEnd = DeclAttrs.end();
683 A != AEnd; ++A)
684 A->second->~AttrVec();
685}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000686
Douglas Gregor00545312010-05-23 18:26:36 +0000687void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
688 Deallocations.push_back(std::make_pair(Callback, Data));
689}
690
Mike Stump1eb44332009-09-09 15:08:12 +0000691void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000692ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000693 ExternalSource.reset(Source.take());
694}
695
Reid Spencer5f016e22007-07-11 17:01:13 +0000696void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000697 llvm::errs() << "\n*** AST Context Stats:\n";
698 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000699
Douglas Gregordbe833d2009-05-26 14:40:08 +0000700 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000701#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000702#define ABSTRACT_TYPE(Name, Parent)
703#include "clang/AST/TypeNodes.def"
704 0 // Extra
705 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000706
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
708 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000709 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 }
711
Douglas Gregordbe833d2009-05-26 14:40:08 +0000712 unsigned Idx = 0;
713 unsigned TotalBytes = 0;
714#define TYPE(Name, Parent) \
715 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000716 llvm::errs() << " " << counts[Idx] << " " << #Name \
717 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000718 TotalBytes += counts[Idx] * sizeof(Name##Type); \
719 ++Idx;
720#define ABSTRACT_TYPE(Name, Parent)
721#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Chandler Carruthcd92a652011-07-04 05:32:14 +0000723 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
724
Douglas Gregor4923aa22010-07-02 20:37:36 +0000725 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000726 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
727 << NumImplicitDefaultConstructors
728 << " implicit default constructors created\n";
729 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
730 << NumImplicitCopyConstructors
731 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000732 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000733 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
734 << NumImplicitMoveConstructors
735 << " implicit move constructors created\n";
736 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
737 << NumImplicitCopyAssignmentOperators
738 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000739 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000740 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
741 << NumImplicitMoveAssignmentOperators
742 << " implicit move assignment operators created\n";
743 llvm::errs() << NumImplicitDestructorsDeclared << "/"
744 << NumImplicitDestructors
745 << " implicit destructors created\n";
746
Douglas Gregor2cf26342009-04-09 22:27:44 +0000747 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000748 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000749 ExternalSource->PrintStats();
750 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000751
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000752 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000753}
754
Douglas Gregor772eeae2011-08-12 06:49:56 +0000755TypedefDecl *ASTContext::getInt128Decl() const {
756 if (!Int128Decl) {
757 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
758 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
759 getTranslationUnitDecl(),
760 SourceLocation(),
761 SourceLocation(),
762 &Idents.get("__int128_t"),
763 TInfo);
764 }
765
766 return Int128Decl;
767}
768
769TypedefDecl *ASTContext::getUInt128Decl() const {
770 if (!UInt128Decl) {
771 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
772 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
773 getTranslationUnitDecl(),
774 SourceLocation(),
775 SourceLocation(),
776 &Idents.get("__uint128_t"),
777 TInfo);
778 }
779
780 return UInt128Decl;
781}
Reid Spencer5f016e22007-07-11 17:01:13 +0000782
John McCalle27ec8a2009-10-23 23:03:21 +0000783void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000784 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000785 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000786 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000787}
788
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000789void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
790 assert((!this->Target || this->Target == &Target) &&
791 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000792 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000794 this->Target = &Target;
795
796 ABI.reset(createCXXABI(Target));
797 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
798
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 // C99 6.2.5p19.
800 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Reid Spencer5f016e22007-07-11 17:01:13 +0000802 // C99 6.2.5p2.
803 InitBuiltinType(BoolTy, BuiltinType::Bool);
804 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000805 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 InitBuiltinType(CharTy, BuiltinType::Char_S);
807 else
808 InitBuiltinType(CharTy, BuiltinType::Char_U);
809 // C99 6.2.5p4.
810 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
811 InitBuiltinType(ShortTy, BuiltinType::Short);
812 InitBuiltinType(IntTy, BuiltinType::Int);
813 InitBuiltinType(LongTy, BuiltinType::Long);
814 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 // C99 6.2.5p6.
817 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
818 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
819 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
820 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
821 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 // C99 6.2.5p10.
824 InitBuiltinType(FloatTy, BuiltinType::Float);
825 InitBuiltinType(DoubleTy, BuiltinType::Double);
826 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000827
Chris Lattner2df9ced2009-04-30 02:43:43 +0000828 // GNU extension, 128-bit integers.
829 InitBuiltinType(Int128Ty, BuiltinType::Int128);
830 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
831
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000832 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000833 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000834 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
835 else // -fshort-wchar makes wchar_t be unsigned.
836 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000837 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000838 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000839
James Molloy392da482012-05-04 10:55:22 +0000840 WIntTy = getFromTargetType(Target.getWIntType());
841
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000842 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
843 InitBuiltinType(Char16Ty, BuiltinType::Char16);
844 else // C99
845 Char16Ty = getFromTargetType(Target.getChar16Type());
846
847 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
848 InitBuiltinType(Char32Ty, BuiltinType::Char32);
849 else // C99
850 Char32Ty = getFromTargetType(Target.getChar32Type());
851
Douglas Gregor898574e2008-12-05 23:32:09 +0000852 // Placeholder type for type-dependent expressions whose type is
853 // completely unknown. No code should ever check a type against
854 // DependentTy and users should never see it; however, it is here to
855 // help diagnose failures to properly check for type-dependent
856 // expressions.
857 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000858
John McCall2a984ca2010-10-12 00:20:44 +0000859 // Placeholder type for functions.
860 InitBuiltinType(OverloadTy, BuiltinType::Overload);
861
John McCall864c0412011-04-26 20:42:42 +0000862 // Placeholder type for bound members.
863 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
864
John McCall3c3b7f92011-10-25 17:37:35 +0000865 // Placeholder type for pseudo-objects.
866 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
867
John McCall1de4d4e2011-04-07 08:22:57 +0000868 // "any" type; useful for debugger-like clients.
869 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
870
John McCall0ddaeb92011-10-17 18:09:15 +0000871 // Placeholder type for unbridged ARC casts.
872 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
873
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000874 // Placeholder type for builtin functions.
875 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // C99 6.2.5p11.
878 FloatComplexTy = getComplexType(FloatTy);
879 DoubleComplexTy = getComplexType(DoubleTy);
880 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000881
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000882 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000883 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
884 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000885 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000886
887 if (LangOpts.OpenCL) {
888 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
889 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
890 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
891 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
892 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
893 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
894 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000895
896 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000897 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
898 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000899
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000900 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000901
902 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000904 // void * type
905 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000906
907 // nullptr type (C++0x 2.14.7)
908 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000909
910 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
911 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000912
913 // Builtin type used to help define __builtin_va_list.
914 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000915}
916
David Blaikied6471f72011-09-25 23:23:43 +0000917DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000918 return SourceMgr.getDiagnostics();
919}
920
Douglas Gregor63200642010-08-30 16:49:28 +0000921AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
922 AttrVec *&Result = DeclAttrs[D];
923 if (!Result) {
924 void *Mem = Allocate(sizeof(AttrVec));
925 Result = new (Mem) AttrVec;
926 }
927
928 return *Result;
929}
930
931/// \brief Erase the attributes corresponding to the given declaration.
932void ASTContext::eraseDeclAttrs(const Decl *D) {
933 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
934 if (Pos != DeclAttrs.end()) {
935 Pos->second->~AttrVec();
936 DeclAttrs.erase(Pos);
937 }
938}
939
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000940MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000941ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000942 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000943 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000944 = InstantiatedFromStaticDataMember.find(Var);
945 if (Pos == InstantiatedFromStaticDataMember.end())
946 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor7caa6822009-07-24 20:34:43 +0000948 return Pos->second;
949}
950
Mike Stump1eb44332009-09-09 15:08:12 +0000951void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000952ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000953 TemplateSpecializationKind TSK,
954 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000955 assert(Inst->isStaticDataMember() && "Not a static data member");
956 assert(Tmpl->isStaticDataMember() && "Not a static data member");
957 assert(!InstantiatedFromStaticDataMember[Inst] &&
958 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000959 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000960 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000961}
962
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000963FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
964 const FunctionDecl *FD){
965 assert(FD && "Specialization is 0");
966 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000967 = ClassScopeSpecializationPattern.find(FD);
968 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000969 return 0;
970
971 return Pos->second;
972}
973
974void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
975 FunctionDecl *Pattern) {
976 assert(FD && "Specialization is 0");
977 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000978 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000979}
980
John McCall7ba107a2009-11-18 02:36:19 +0000981NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000982ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000983 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000984 = InstantiatedFromUsingDecl.find(UUD);
985 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000986 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Anders Carlsson0d8df782009-08-29 19:37:28 +0000988 return Pos->second;
989}
990
991void
John McCalled976492009-12-04 22:46:56 +0000992ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
993 assert((isa<UsingDecl>(Pattern) ||
994 isa<UnresolvedUsingValueDecl>(Pattern) ||
995 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
996 "pattern decl is not a using decl");
997 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
998 InstantiatedFromUsingDecl[Inst] = Pattern;
999}
1000
1001UsingShadowDecl *
1002ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1003 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1004 = InstantiatedFromUsingShadowDecl.find(Inst);
1005 if (Pos == InstantiatedFromUsingShadowDecl.end())
1006 return 0;
1007
1008 return Pos->second;
1009}
1010
1011void
1012ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1013 UsingShadowDecl *Pattern) {
1014 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1015 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001016}
1017
Anders Carlssond8b285f2009-09-01 04:26:58 +00001018FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1019 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1020 = InstantiatedFromUnnamedFieldDecl.find(Field);
1021 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1022 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Anders Carlssond8b285f2009-09-01 04:26:58 +00001024 return Pos->second;
1025}
1026
1027void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1028 FieldDecl *Tmpl) {
1029 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1030 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1031 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1032 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Anders Carlssond8b285f2009-09-01 04:26:58 +00001034 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1035}
1036
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001037bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1038 const FieldDecl *LastFD) const {
1039 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001040 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001041}
1042
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001043bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1044 const FieldDecl *LastFD) const {
1045 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001046 FD->getBitWidthValue(*this) == 0 &&
1047 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001048}
1049
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001050bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1051 const FieldDecl *LastFD) const {
1052 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001053 FD->getBitWidthValue(*this) &&
1054 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001055}
1056
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001057bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001058 const FieldDecl *LastFD) const {
1059 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001060 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001061}
1062
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001063bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001064 const FieldDecl *LastFD) const {
1065 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001066 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001067}
1068
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001069ASTContext::overridden_cxx_method_iterator
1070ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1071 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001072 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001073 if (Pos == OverriddenMethods.end())
1074 return 0;
1075
1076 return Pos->second.begin();
1077}
1078
1079ASTContext::overridden_cxx_method_iterator
1080ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1081 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001082 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001083 if (Pos == OverriddenMethods.end())
1084 return 0;
1085
1086 return Pos->second.end();
1087}
1088
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001089unsigned
1090ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1091 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001092 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001093 if (Pos == OverriddenMethods.end())
1094 return 0;
1095
1096 return Pos->second.size();
1097}
1098
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001099void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1100 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001101 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001102 OverriddenMethods[Method].push_back(Overridden);
1103}
1104
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001105void ASTContext::getOverriddenMethods(
1106 const NamedDecl *D,
1107 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001108 assert(D);
1109
1110 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001111 Overridden.append(CXXMethod->begin_overridden_methods(),
1112 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001113 return;
1114 }
1115
1116 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1117 if (!Method)
1118 return;
1119
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001120 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1121 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001122 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001123}
1124
Douglas Gregore6649772011-12-03 00:30:27 +00001125void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1126 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1127 assert(!Import->isFromASTFile() && "Non-local import declaration");
1128 if (!FirstLocalImport) {
1129 FirstLocalImport = Import;
1130 LastLocalImport = Import;
1131 return;
1132 }
1133
1134 LastLocalImport->NextLocalImport = Import;
1135 LastLocalImport = Import;
1136}
1137
Chris Lattner464175b2007-07-18 17:52:12 +00001138//===----------------------------------------------------------------------===//
1139// Type Sizing and Analysis
1140//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001141
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001142/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1143/// scalar floating point type.
1144const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001145 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001146 assert(BT && "Not a floating point type!");
1147 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001148 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001149 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001150 case BuiltinType::Float: return Target->getFloatFormat();
1151 case BuiltinType::Double: return Target->getDoubleFormat();
1152 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001153 }
1154}
1155
Ken Dyck8b752f12010-01-27 17:10:57 +00001156/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001157/// specified decl. Note that bitfields do not have a valid alignment, so
1158/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001159/// If @p RefAsPointee, references are treated like their underlying type
1160/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001161CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001162 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001163
John McCall4081a5c2010-10-08 18:24:19 +00001164 bool UseAlignAttrOnly = false;
1165 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1166 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001167
John McCall4081a5c2010-10-08 18:24:19 +00001168 // __attribute__((aligned)) can increase or decrease alignment
1169 // *except* on a struct or struct member, where it only increases
1170 // alignment unless 'packed' is also specified.
1171 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001172 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001173 // ignore that possibility; Sema should diagnose it.
1174 if (isa<FieldDecl>(D)) {
1175 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1176 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1177 } else {
1178 UseAlignAttrOnly = true;
1179 }
1180 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001181 else if (isa<FieldDecl>(D))
1182 UseAlignAttrOnly =
1183 D->hasAttr<PackedAttr>() ||
1184 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001185
John McCallba4f5d52011-01-20 07:57:12 +00001186 // If we're using the align attribute only, just ignore everything
1187 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001188 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001189 // do nothing
1190
John McCall4081a5c2010-10-08 18:24:19 +00001191 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001192 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001193 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001194 if (RefAsPointee)
1195 T = RT->getPointeeType();
1196 else
1197 T = getPointerType(RT->getPointeeType());
1198 }
1199 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001200 // Adjust alignments of declarations with array type by the
1201 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001202 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001203 const ArrayType *arrayType;
1204 if (MinWidth && (arrayType = getAsArrayType(T))) {
1205 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001206 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001207 else if (isa<ConstantArrayType>(arrayType) &&
1208 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001209 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001210
John McCall3b657512011-01-19 10:06:00 +00001211 // Walk through any array types while we're at it.
1212 T = getBaseElementType(arrayType);
1213 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001214 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001215 }
John McCallba4f5d52011-01-20 07:57:12 +00001216
1217 // Fields can be subject to extra alignment constraints, like if
1218 // the field is packed, the struct is packed, or the struct has a
1219 // a max-field-alignment constraint (#pragma pack). So calculate
1220 // the actual alignment of the field within the struct, and then
1221 // (as we're expected to) constrain that by the alignment of the type.
1222 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1223 // So calculate the alignment of the field.
1224 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1225
1226 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001227 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001228
1229 // Use the GCD of that and the offset within the record.
1230 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1231 if (offset > 0) {
1232 // Alignment is always a power of 2, so the GCD will be a power of 2,
1233 // which means we get to do this crazy thing instead of Euclid's.
1234 uint64_t lowBitOfOffset = offset & (~offset + 1);
1235 if (lowBitOfOffset < fieldAlign)
1236 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1237 }
1238
1239 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001240 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001241 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001242
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001243 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001244}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001245
John McCall929bbfb2012-08-21 04:10:00 +00001246// getTypeInfoDataSizeInChars - Return the size of a type, in
1247// chars. If the type is a record, its data size is returned. This is
1248// the size of the memcpy that's performed when assigning this type
1249// using a trivial copy/move assignment operator.
1250std::pair<CharUnits, CharUnits>
1251ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1252 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1253
1254 // In C++, objects can sometimes be allocated into the tail padding
1255 // of a base-class subobject. We decide whether that's possible
1256 // during class layout, so here we can just trust the layout results.
1257 if (getLangOpts().CPlusPlus) {
1258 if (const RecordType *RT = T->getAs<RecordType>()) {
1259 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1260 sizeAndAlign.first = layout.getDataSize();
1261 }
1262 }
1263
1264 return sizeAndAlign;
1265}
1266
John McCallea1471e2010-05-20 01:18:31 +00001267std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001268ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001269 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001270 return std::make_pair(toCharUnitsFromBits(Info.first),
1271 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001272}
1273
1274std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001275ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001276 return getTypeInfoInChars(T.getTypePtr());
1277}
1278
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001279std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1280 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1281 if (it != MemoizedTypeInfo.end())
1282 return it->second;
1283
1284 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1285 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1286 return Info;
1287}
1288
1289/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1290/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001291///
1292/// FIXME: Pointers into different addr spaces could have different sizes and
1293/// alignment requirements: getPointerInfo should take an AddrSpace, this
1294/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001295std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001296ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001297 uint64_t Width=0;
1298 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001299 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001300#define TYPE(Class, Base)
1301#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001302#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001303#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1304#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001305 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001306
Chris Lattner692233e2007-07-13 22:27:08 +00001307 case Type::FunctionNoProto:
1308 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001309 // GCC extension: alignof(function) = 32 bits
1310 Width = 0;
1311 Align = 32;
1312 break;
1313
Douglas Gregor72564e72009-02-26 23:50:07 +00001314 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001315 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001316 Width = 0;
1317 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1318 break;
1319
Steve Narofffb22d962007-08-30 01:06:46 +00001320 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001321 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Chris Lattner98be4942008-03-05 18:54:05 +00001323 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001324 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001325 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1326 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001327 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001328 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001329 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001330 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001331 }
Nate Begeman213541a2008-04-18 23:10:10 +00001332 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001333 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001334 const VectorType *VT = cast<VectorType>(T);
1335 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1336 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001337 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001338 // If the alignment is not a power of 2, round up to the next power of 2.
1339 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001340 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001341 Align = llvm::NextPowerOf2(Align);
1342 Width = llvm::RoundUpToAlignment(Width, Align);
1343 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001344 // Adjust the alignment based on the target max.
1345 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1346 if (TargetVectorAlign && TargetVectorAlign < Align)
1347 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001348 break;
1349 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001350
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001351 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001352 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001353 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001354 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001355 // GCC extension: alignof(void) = 8 bits.
1356 Width = 0;
1357 Align = 8;
1358 break;
1359
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001360 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001361 Width = Target->getBoolWidth();
1362 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001363 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001364 case BuiltinType::Char_S:
1365 case BuiltinType::Char_U:
1366 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001367 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001368 Width = Target->getCharWidth();
1369 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001370 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001371 case BuiltinType::WChar_S:
1372 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001373 Width = Target->getWCharWidth();
1374 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001375 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001376 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001377 Width = Target->getChar16Width();
1378 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001379 break;
1380 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001381 Width = Target->getChar32Width();
1382 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001383 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001384 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001385 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001386 Width = Target->getShortWidth();
1387 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001388 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001389 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001390 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001391 Width = Target->getIntWidth();
1392 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001393 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001394 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001395 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001396 Width = Target->getLongWidth();
1397 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001398 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001399 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001400 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001401 Width = Target->getLongLongWidth();
1402 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001403 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001404 case BuiltinType::Int128:
1405 case BuiltinType::UInt128:
1406 Width = 128;
1407 Align = 128; // int128_t is 128-bit aligned on all targets.
1408 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001409 case BuiltinType::Half:
1410 Width = Target->getHalfWidth();
1411 Align = Target->getHalfAlign();
1412 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001413 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001414 Width = Target->getFloatWidth();
1415 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001416 break;
1417 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001418 Width = Target->getDoubleWidth();
1419 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001420 break;
1421 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001422 Width = Target->getLongDoubleWidth();
1423 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001424 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001425 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001426 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1427 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001428 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001429 case BuiltinType::ObjCId:
1430 case BuiltinType::ObjCClass:
1431 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001432 Width = Target->getPointerWidth(0);
1433 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001434 break;
Guy Benyeib13621d2012-12-18 14:38:23 +00001435 case BuiltinType::OCLImage1d:
1436 case BuiltinType::OCLImage1dArray:
1437 case BuiltinType::OCLImage1dBuffer:
1438 case BuiltinType::OCLImage2d:
1439 case BuiltinType::OCLImage2dArray:
1440 case BuiltinType::OCLImage3d:
1441 // Currently these types are pointers to opaque types.
1442 Width = Target->getPointerWidth(0);
1443 Align = Target->getPointerAlign(0);
1444 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001445 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001446 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001447 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001448 Width = Target->getPointerWidth(0);
1449 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001450 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001451 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001452 unsigned AS = getTargetAddressSpace(
1453 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001454 Width = Target->getPointerWidth(AS);
1455 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001456 break;
1457 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001458 case Type::LValueReference:
1459 case Type::RValueReference: {
1460 // alignof and sizeof should never enter this code path here, so we go
1461 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001462 unsigned AS = getTargetAddressSpace(
1463 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001464 Width = Target->getPointerWidth(AS);
1465 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001466 break;
1467 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001468 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001469 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001470 Width = Target->getPointerWidth(AS);
1471 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001472 break;
1473 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001474 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001475 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001476 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001477 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001478 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001479 Align = PtrDiffInfo.second;
1480 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001481 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001482 case Type::Complex: {
1483 // Complex types have the same alignment as their elements, but twice the
1484 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001485 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001486 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001487 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001488 Align = EltInfo.second;
1489 break;
1490 }
John McCallc12c5bb2010-05-15 11:32:37 +00001491 case Type::ObjCObject:
1492 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001493 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001494 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001495 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001496 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001497 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001498 break;
1499 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001500 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001501 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001502 const TagType *TT = cast<TagType>(T);
1503
1504 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001505 Width = 8;
1506 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001507 break;
1508 }
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Daniel Dunbar1d751182008-11-08 05:48:37 +00001510 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001511 return getTypeInfo(ET->getDecl()->getIntegerType());
1512
Daniel Dunbar1d751182008-11-08 05:48:37 +00001513 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001514 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001515 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001516 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001517 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001518 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001519
Chris Lattner9fcfe922009-10-22 05:17:15 +00001520 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001521 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1522 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001523
Richard Smith34b41d92011-02-20 03:19:35 +00001524 case Type::Auto: {
1525 const AutoType *A = cast<AutoType>(T);
1526 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001527 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001528 }
1529
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001530 case Type::Paren:
1531 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1532
Douglas Gregor18857642009-04-30 17:32:17 +00001533 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001534 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001535 std::pair<uint64_t, unsigned> Info
1536 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001537 // If the typedef has an aligned attribute on it, it overrides any computed
1538 // alignment we have. This violates the GCC documentation (which says that
1539 // attribute(aligned) can only round up) but matches its implementation.
1540 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1541 Align = AttrAlign;
1542 else
1543 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001544 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001545 break;
Chris Lattner71763312008-04-06 22:05:18 +00001546 }
Douglas Gregor18857642009-04-30 17:32:17 +00001547
1548 case Type::TypeOfExpr:
1549 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1550 .getTypePtr());
1551
1552 case Type::TypeOf:
1553 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1554
Anders Carlsson395b4752009-06-24 19:06:50 +00001555 case Type::Decltype:
1556 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1557 .getTypePtr());
1558
Sean Huntca63c202011-05-24 22:41:36 +00001559 case Type::UnaryTransform:
1560 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1561
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001562 case Type::Elaborated:
1563 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001564
John McCall9d156a72011-01-06 01:58:22 +00001565 case Type::Attributed:
1566 return getTypeInfo(
1567 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1568
Richard Smith3e4c6c42011-05-05 21:57:07 +00001569 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001570 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001571 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001572 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1573 // A type alias template specialization may refer to a typedef with the
1574 // aligned attribute on it.
1575 if (TST->isTypeAlias())
1576 return getTypeInfo(TST->getAliasedType().getTypePtr());
1577 else
1578 return getTypeInfo(getCanonicalType(T));
1579 }
1580
Eli Friedmanb001de72011-10-06 23:00:33 +00001581 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001582 std::pair<uint64_t, unsigned> Info
1583 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1584 Width = Info.first;
1585 Align = Info.second;
1586 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1587 llvm::isPowerOf2_64(Width)) {
1588 // We can potentially perform lock-free atomic operations for this
1589 // type; promote the alignment appropriately.
1590 // FIXME: We could potentially promote the width here as well...
1591 // is that worthwhile? (Non-struct atomic types generally have
1592 // power-of-two size anyway, but structs might not. Requires a bit
1593 // of implementation work to make sure we zero out the extra bits.)
1594 Align = static_cast<unsigned>(Width);
1595 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001596 }
1597
Douglas Gregor18857642009-04-30 17:32:17 +00001598 }
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Eli Friedman2be46072011-10-14 20:59:01 +00001600 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001601 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001602}
1603
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001604/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1605CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1606 return CharUnits::fromQuantity(BitSize / getCharWidth());
1607}
1608
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001609/// toBits - Convert a size in characters to a size in characters.
1610int64_t ASTContext::toBits(CharUnits CharSize) const {
1611 return CharSize.getQuantity() * getCharWidth();
1612}
1613
Ken Dyckbdc601b2009-12-22 14:23:30 +00001614/// getTypeSizeInChars - Return the size of the specified type, in characters.
1615/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001616CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001617 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001618}
Jay Foad4ba2a172011-01-12 09:06:06 +00001619CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001620 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001621}
1622
Ken Dyck16e20cc2010-01-26 17:25:18 +00001623/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001624/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001625CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001626 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001627}
Jay Foad4ba2a172011-01-12 09:06:06 +00001628CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001629 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001630}
1631
Chris Lattner34ebde42009-01-27 18:08:34 +00001632/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1633/// type for the current target in bits. This can be different than the ABI
1634/// alignment in cases where it is beneficial for performance to overalign
1635/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001636unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001637 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001638
1639 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001640 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001641 T = CT->getElementType().getTypePtr();
1642 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001643 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1644 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001645 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1646
Chris Lattner34ebde42009-01-27 18:08:34 +00001647 return ABIAlign;
1648}
1649
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001650/// DeepCollectObjCIvars -
1651/// This routine first collects all declared, but not synthesized, ivars in
1652/// super class and then collects all ivars, including those synthesized for
1653/// current class. This routine is used for implementation of current class
1654/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001655///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001656void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1657 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001658 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001659 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1660 DeepCollectObjCIvars(SuperClass, false, Ivars);
1661 if (!leafClass) {
1662 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1663 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001664 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001665 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001666 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001667 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001668 Iv= Iv->getNextIvar())
1669 Ivars.push_back(Iv);
1670 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001671}
1672
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001673/// CollectInheritedProtocols - Collect all protocols in current class and
1674/// those inherited by it.
1675void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001676 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001677 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001678 // We can use protocol_iterator here instead of
1679 // all_referenced_protocol_iterator since we are walking all categories.
1680 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1681 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001682 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001683 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001684 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001685 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001686 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001687 CollectInheritedProtocols(*P, Protocols);
1688 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001689 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001690
1691 // Categories of this Interface.
1692 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1693 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1694 CollectInheritedProtocols(CDeclChain, Protocols);
1695 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1696 while (SD) {
1697 CollectInheritedProtocols(SD, Protocols);
1698 SD = SD->getSuperClass();
1699 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001700 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001701 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001702 PE = OC->protocol_end(); P != PE; ++P) {
1703 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001704 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001705 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1706 PE = Proto->protocol_end(); P != PE; ++P)
1707 CollectInheritedProtocols(*P, Protocols);
1708 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001709 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001710 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1711 PE = OP->protocol_end(); P != PE; ++P) {
1712 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001713 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001714 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1715 PE = Proto->protocol_end(); P != PE; ++P)
1716 CollectInheritedProtocols(*P, Protocols);
1717 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001718 }
1719}
1720
Jay Foad4ba2a172011-01-12 09:06:06 +00001721unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001722 unsigned count = 0;
1723 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001724 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1725 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001726 count += CDecl->ivar_size();
1727
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001728 // Count ivar defined in this class's implementation. This
1729 // includes synthesized ivars.
1730 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001731 count += ImplDecl->ivar_size();
1732
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001733 return count;
1734}
1735
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001736bool ASTContext::isSentinelNullExpr(const Expr *E) {
1737 if (!E)
1738 return false;
1739
1740 // nullptr_t is always treated as null.
1741 if (E->getType()->isNullPtrType()) return true;
1742
1743 if (E->getType()->isAnyPointerType() &&
1744 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1745 Expr::NPC_ValueDependentIsNull))
1746 return true;
1747
1748 // Unfortunately, __null has type 'int'.
1749 if (isa<GNUNullExpr>(E)) return true;
1750
1751 return false;
1752}
1753
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001754/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1755ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1756 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1757 I = ObjCImpls.find(D);
1758 if (I != ObjCImpls.end())
1759 return cast<ObjCImplementationDecl>(I->second);
1760 return 0;
1761}
1762/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1763ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1764 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1765 I = ObjCImpls.find(D);
1766 if (I != ObjCImpls.end())
1767 return cast<ObjCCategoryImplDecl>(I->second);
1768 return 0;
1769}
1770
1771/// \brief Set the implementation of ObjCInterfaceDecl.
1772void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1773 ObjCImplementationDecl *ImplD) {
1774 assert(IFaceD && ImplD && "Passed null params");
1775 ObjCImpls[IFaceD] = ImplD;
1776}
1777/// \brief Set the implementation of ObjCCategoryDecl.
1778void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1779 ObjCCategoryImplDecl *ImplD) {
1780 assert(CatD && ImplD && "Passed null params");
1781 ObjCImpls[CatD] = ImplD;
1782}
1783
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001784ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1785 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1786 return ID;
1787 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1788 return CD->getClassInterface();
1789 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1790 return IMD->getClassInterface();
1791
1792 return 0;
1793}
1794
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001795/// \brief Get the copy initialization expression of VarDecl,or NULL if
1796/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001797Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001798 assert(VD && "Passed null params");
1799 assert(VD->hasAttr<BlocksAttr>() &&
1800 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001801 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001802 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001803 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1804}
1805
1806/// \brief Set the copy inialization expression of a block var decl.
1807void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1808 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001809 assert(VD->hasAttr<BlocksAttr>() &&
1810 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001811 BlockVarCopyInits[VD] = Init;
1812}
1813
John McCalla93c9342009-12-07 02:54:59 +00001814TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001815 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001816 if (!DataSize)
1817 DataSize = TypeLoc::getFullDataSizeForType(T);
1818 else
1819 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001820 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001821
John McCalla93c9342009-12-07 02:54:59 +00001822 TypeSourceInfo *TInfo =
1823 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1824 new (TInfo) TypeSourceInfo(T);
1825 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001826}
1827
John McCalla93c9342009-12-07 02:54:59 +00001828TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001829 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001830 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001831 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001832 return DI;
1833}
1834
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001835const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001836ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001837 return getObjCLayout(D, 0);
1838}
1839
1840const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001841ASTContext::getASTObjCImplementationLayout(
1842 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001843 return getObjCLayout(D->getClassInterface(), D);
1844}
1845
Chris Lattnera7674d82007-07-13 22:13:22 +00001846//===----------------------------------------------------------------------===//
1847// Type creation/memoization methods
1848//===----------------------------------------------------------------------===//
1849
Jay Foad4ba2a172011-01-12 09:06:06 +00001850QualType
John McCall3b657512011-01-19 10:06:00 +00001851ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1852 unsigned fastQuals = quals.getFastQualifiers();
1853 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001854
1855 // Check if we've already instantiated this type.
1856 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001857 ExtQuals::Profile(ID, baseType, quals);
1858 void *insertPos = 0;
1859 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1860 assert(eq->getQualifiers() == quals);
1861 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001862 }
1863
John McCall3b657512011-01-19 10:06:00 +00001864 // If the base type is not canonical, make the appropriate canonical type.
1865 QualType canon;
1866 if (!baseType->isCanonicalUnqualified()) {
1867 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001868 canonSplit.Quals.addConsistentQualifiers(quals);
1869 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001870
1871 // Re-find the insert position.
1872 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1873 }
1874
1875 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1876 ExtQualNodes.InsertNode(eq, insertPos);
1877 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001878}
1879
Jay Foad4ba2a172011-01-12 09:06:06 +00001880QualType
1881ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001882 QualType CanT = getCanonicalType(T);
1883 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001884 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001885
John McCall0953e762009-09-24 19:53:00 +00001886 // If we are composing extended qualifiers together, merge together
1887 // into one ExtQuals node.
1888 QualifierCollector Quals;
1889 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001890
John McCall0953e762009-09-24 19:53:00 +00001891 // If this type already has an address space specified, it cannot get
1892 // another one.
1893 assert(!Quals.hasAddressSpace() &&
1894 "Type cannot be in multiple addr spaces!");
1895 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001896
John McCall0953e762009-09-24 19:53:00 +00001897 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001898}
1899
Chris Lattnerb7d25532009-02-18 22:53:11 +00001900QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001901 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001902 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001903 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001904 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001905
John McCall7f040a92010-12-24 02:08:15 +00001906 if (const PointerType *ptr = T->getAs<PointerType>()) {
1907 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001908 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001909 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1910 return getPointerType(ResultType);
1911 }
1912 }
Mike Stump1eb44332009-09-09 15:08:12 +00001913
John McCall0953e762009-09-24 19:53:00 +00001914 // If we are composing extended qualifiers together, merge together
1915 // into one ExtQuals node.
1916 QualifierCollector Quals;
1917 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001918
John McCall0953e762009-09-24 19:53:00 +00001919 // If this type already has an ObjCGC specified, it cannot get
1920 // another one.
1921 assert(!Quals.hasObjCGCAttr() &&
1922 "Type cannot have multiple ObjCGCs!");
1923 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001924
John McCall0953e762009-09-24 19:53:00 +00001925 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001926}
Chris Lattnera7674d82007-07-13 22:13:22 +00001927
John McCalle6a365d2010-12-19 02:44:49 +00001928const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1929 FunctionType::ExtInfo Info) {
1930 if (T->getExtInfo() == Info)
1931 return T;
1932
1933 QualType Result;
1934 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1935 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1936 } else {
1937 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1938 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1939 EPI.ExtInfo = Info;
1940 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1941 FPT->getNumArgs(), EPI);
1942 }
1943
1944 return cast<FunctionType>(Result.getTypePtr());
1945}
1946
Reid Spencer5f016e22007-07-11 17:01:13 +00001947/// getComplexType - Return the uniqued reference to the type for a complex
1948/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001949QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 // Unique pointers, to guarantee there is only one pointer of a particular
1951 // structure.
1952 llvm::FoldingSetNodeID ID;
1953 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 void *InsertPos = 0;
1956 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1957 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 // If the pointee type isn't canonical, this won't be a canonical type either,
1960 // so fill in the canonical type field.
1961 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001962 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001963 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 // Get the new insert position for the node we care about.
1966 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001967 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 }
John McCall6b304a02009-09-24 23:30:46 +00001969 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 Types.push_back(New);
1971 ComplexTypes.InsertNode(New, InsertPos);
1972 return QualType(New, 0);
1973}
1974
Reid Spencer5f016e22007-07-11 17:01:13 +00001975/// getPointerType - Return the uniqued reference to the type for a pointer to
1976/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001977QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // Unique pointers, to guarantee there is only one pointer of a particular
1979 // structure.
1980 llvm::FoldingSetNodeID ID;
1981 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 void *InsertPos = 0;
1984 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1985 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 // If the pointee type isn't canonical, this won't be a canonical type either,
1988 // so fill in the canonical type field.
1989 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001990 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001991 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 // Get the new insert position for the node we care about.
1994 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001995 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 }
John McCall6b304a02009-09-24 23:30:46 +00001997 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 Types.push_back(New);
1999 PointerTypes.InsertNode(New, InsertPos);
2000 return QualType(New, 0);
2001}
2002
Mike Stump1eb44332009-09-09 15:08:12 +00002003/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002004/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002005QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002006 assert(T->isFunctionType() && "block of function types only");
2007 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002008 // structure.
2009 llvm::FoldingSetNodeID ID;
2010 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Steve Naroff5618bd42008-08-27 16:04:49 +00002012 void *InsertPos = 0;
2013 if (BlockPointerType *PT =
2014 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2015 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002016
2017 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002018 // type either so fill in the canonical type field.
2019 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002020 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002021 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Steve Naroff5618bd42008-08-27 16:04:49 +00002023 // Get the new insert position for the node we care about.
2024 BlockPointerType *NewIP =
2025 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002026 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002027 }
John McCall6b304a02009-09-24 23:30:46 +00002028 BlockPointerType *New
2029 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002030 Types.push_back(New);
2031 BlockPointerTypes.InsertNode(New, InsertPos);
2032 return QualType(New, 0);
2033}
2034
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002035/// getLValueReferenceType - Return the uniqued reference to the type for an
2036/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002037QualType
2038ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002039 assert(getCanonicalType(T) != OverloadTy &&
2040 "Unresolved overloaded function type");
2041
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 // Unique pointers, to guarantee there is only one pointer of a particular
2043 // structure.
2044 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002045 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002046
2047 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002048 if (LValueReferenceType *RT =
2049 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002051
John McCall54e14c42009-10-22 22:37:11 +00002052 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2053
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 // If the referencee type isn't canonical, this won't be a canonical type
2055 // either, so fill in the canonical type field.
2056 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002057 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2058 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2059 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002060
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002062 LValueReferenceType *NewIP =
2063 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002064 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 }
2066
John McCall6b304a02009-09-24 23:30:46 +00002067 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002068 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2069 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002070 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002071 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002072
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002073 return QualType(New, 0);
2074}
2075
2076/// getRValueReferenceType - Return the uniqued reference to the type for an
2077/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002078QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002079 // Unique pointers, to guarantee there is only one pointer of a particular
2080 // structure.
2081 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002082 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002083
2084 void *InsertPos = 0;
2085 if (RValueReferenceType *RT =
2086 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2087 return QualType(RT, 0);
2088
John McCall54e14c42009-10-22 22:37:11 +00002089 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2090
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002091 // If the referencee type isn't canonical, this won't be a canonical type
2092 // either, so fill in the canonical type field.
2093 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002094 if (InnerRef || !T.isCanonical()) {
2095 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2096 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002097
2098 // Get the new insert position for the node we care about.
2099 RValueReferenceType *NewIP =
2100 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002101 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002102 }
2103
John McCall6b304a02009-09-24 23:30:46 +00002104 RValueReferenceType *New
2105 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002106 Types.push_back(New);
2107 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 return QualType(New, 0);
2109}
2110
Sebastian Redlf30208a2009-01-24 21:16:55 +00002111/// getMemberPointerType - Return the uniqued reference to the type for a
2112/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002113QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002114 // Unique pointers, to guarantee there is only one pointer of a particular
2115 // structure.
2116 llvm::FoldingSetNodeID ID;
2117 MemberPointerType::Profile(ID, T, Cls);
2118
2119 void *InsertPos = 0;
2120 if (MemberPointerType *PT =
2121 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2122 return QualType(PT, 0);
2123
2124 // If the pointee or class type isn't canonical, this won't be a canonical
2125 // type either, so fill in the canonical type field.
2126 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002127 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002128 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2129
2130 // Get the new insert position for the node we care about.
2131 MemberPointerType *NewIP =
2132 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002133 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002134 }
John McCall6b304a02009-09-24 23:30:46 +00002135 MemberPointerType *New
2136 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002137 Types.push_back(New);
2138 MemberPointerTypes.InsertNode(New, InsertPos);
2139 return QualType(New, 0);
2140}
2141
Mike Stump1eb44332009-09-09 15:08:12 +00002142/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002143/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002144QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002145 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002146 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002147 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002148 assert((EltTy->isDependentType() ||
2149 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002150 "Constant array of VLAs is illegal!");
2151
Chris Lattner38aeec72009-05-13 04:12:56 +00002152 // Convert the array size into a canonical width matching the pointer size for
2153 // the target.
2154 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002155 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002156 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Reid Spencer5f016e22007-07-11 17:01:13 +00002158 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002159 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002162 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002163 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002165
John McCall3b657512011-01-19 10:06:00 +00002166 // If the element type isn't canonical or has qualifiers, this won't
2167 // be a canonical type either, so fill in the canonical type field.
2168 QualType Canon;
2169 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2170 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002171 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002172 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002173 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002174
Reid Spencer5f016e22007-07-11 17:01:13 +00002175 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002176 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002177 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002178 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 }
Mike Stump1eb44332009-09-09 15:08:12 +00002180
John McCall6b304a02009-09-24 23:30:46 +00002181 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002182 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002183 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 Types.push_back(New);
2185 return QualType(New, 0);
2186}
2187
John McCallce889032011-01-18 08:40:38 +00002188/// getVariableArrayDecayedType - Turns the given type, which may be
2189/// variably-modified, into the corresponding type with all the known
2190/// sizes replaced with [*].
2191QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2192 // Vastly most common case.
2193 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002194
John McCallce889032011-01-18 08:40:38 +00002195 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002196
John McCallce889032011-01-18 08:40:38 +00002197 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002198 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002199 switch (ty->getTypeClass()) {
2200#define TYPE(Class, Base)
2201#define ABSTRACT_TYPE(Class, Base)
2202#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2203#include "clang/AST/TypeNodes.def"
2204 llvm_unreachable("didn't desugar past all non-canonical types?");
2205
2206 // These types should never be variably-modified.
2207 case Type::Builtin:
2208 case Type::Complex:
2209 case Type::Vector:
2210 case Type::ExtVector:
2211 case Type::DependentSizedExtVector:
2212 case Type::ObjCObject:
2213 case Type::ObjCInterface:
2214 case Type::ObjCObjectPointer:
2215 case Type::Record:
2216 case Type::Enum:
2217 case Type::UnresolvedUsing:
2218 case Type::TypeOfExpr:
2219 case Type::TypeOf:
2220 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002221 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002222 case Type::DependentName:
2223 case Type::InjectedClassName:
2224 case Type::TemplateSpecialization:
2225 case Type::DependentTemplateSpecialization:
2226 case Type::TemplateTypeParm:
2227 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002228 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002229 case Type::PackExpansion:
2230 llvm_unreachable("type should never be variably-modified");
2231
2232 // These types can be variably-modified but should never need to
2233 // further decay.
2234 case Type::FunctionNoProto:
2235 case Type::FunctionProto:
2236 case Type::BlockPointer:
2237 case Type::MemberPointer:
2238 return type;
2239
2240 // These types can be variably-modified. All these modifications
2241 // preserve structure except as noted by comments.
2242 // TODO: if we ever care about optimizing VLAs, there are no-op
2243 // optimizations available here.
2244 case Type::Pointer:
2245 result = getPointerType(getVariableArrayDecayedType(
2246 cast<PointerType>(ty)->getPointeeType()));
2247 break;
2248
2249 case Type::LValueReference: {
2250 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2251 result = getLValueReferenceType(
2252 getVariableArrayDecayedType(lv->getPointeeType()),
2253 lv->isSpelledAsLValue());
2254 break;
2255 }
2256
2257 case Type::RValueReference: {
2258 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2259 result = getRValueReferenceType(
2260 getVariableArrayDecayedType(lv->getPointeeType()));
2261 break;
2262 }
2263
Eli Friedmanb001de72011-10-06 23:00:33 +00002264 case Type::Atomic: {
2265 const AtomicType *at = cast<AtomicType>(ty);
2266 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2267 break;
2268 }
2269
John McCallce889032011-01-18 08:40:38 +00002270 case Type::ConstantArray: {
2271 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2272 result = getConstantArrayType(
2273 getVariableArrayDecayedType(cat->getElementType()),
2274 cat->getSize(),
2275 cat->getSizeModifier(),
2276 cat->getIndexTypeCVRQualifiers());
2277 break;
2278 }
2279
2280 case Type::DependentSizedArray: {
2281 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2282 result = getDependentSizedArrayType(
2283 getVariableArrayDecayedType(dat->getElementType()),
2284 dat->getSizeExpr(),
2285 dat->getSizeModifier(),
2286 dat->getIndexTypeCVRQualifiers(),
2287 dat->getBracketsRange());
2288 break;
2289 }
2290
2291 // Turn incomplete types into [*] types.
2292 case Type::IncompleteArray: {
2293 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2294 result = getVariableArrayType(
2295 getVariableArrayDecayedType(iat->getElementType()),
2296 /*size*/ 0,
2297 ArrayType::Normal,
2298 iat->getIndexTypeCVRQualifiers(),
2299 SourceRange());
2300 break;
2301 }
2302
2303 // Turn VLA types into [*] types.
2304 case Type::VariableArray: {
2305 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2306 result = getVariableArrayType(
2307 getVariableArrayDecayedType(vat->getElementType()),
2308 /*size*/ 0,
2309 ArrayType::Star,
2310 vat->getIndexTypeCVRQualifiers(),
2311 vat->getBracketsRange());
2312 break;
2313 }
2314 }
2315
2316 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002317 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002318}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002319
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002320/// getVariableArrayType - Returns a non-unique reference to the type for a
2321/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002322QualType ASTContext::getVariableArrayType(QualType EltTy,
2323 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002324 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002325 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002326 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002327 // Since we don't unique expressions, it isn't possible to unique VLA's
2328 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002329 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002330
John McCall3b657512011-01-19 10:06:00 +00002331 // Be sure to pull qualifiers off the element type.
2332 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2333 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002334 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002335 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002336 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002337 }
2338
John McCall6b304a02009-09-24 23:30:46 +00002339 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002340 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002341
2342 VariableArrayTypes.push_back(New);
2343 Types.push_back(New);
2344 return QualType(New, 0);
2345}
2346
Douglas Gregor898574e2008-12-05 23:32:09 +00002347/// getDependentSizedArrayType - Returns a non-unique reference to
2348/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002349/// type.
John McCall3b657512011-01-19 10:06:00 +00002350QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2351 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002352 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002353 unsigned elementTypeQuals,
2354 SourceRange brackets) const {
2355 assert((!numElements || numElements->isTypeDependent() ||
2356 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002357 "Size must be type- or value-dependent!");
2358
John McCall3b657512011-01-19 10:06:00 +00002359 // Dependently-sized array types that do not have a specified number
2360 // of elements will have their sizes deduced from a dependent
2361 // initializer. We do no canonicalization here at all, which is okay
2362 // because they can't be used in most locations.
2363 if (!numElements) {
2364 DependentSizedArrayType *newType
2365 = new (*this, TypeAlignment)
2366 DependentSizedArrayType(*this, elementType, QualType(),
2367 numElements, ASM, elementTypeQuals,
2368 brackets);
2369 Types.push_back(newType);
2370 return QualType(newType, 0);
2371 }
2372
2373 // Otherwise, we actually build a new type every time, but we
2374 // also build a canonical type.
2375
2376 SplitQualType canonElementType = getCanonicalType(elementType).split();
2377
2378 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002379 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002380 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002381 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002382 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002383
John McCall3b657512011-01-19 10:06:00 +00002384 // Look for an existing type with these properties.
2385 DependentSizedArrayType *canonTy =
2386 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002387
John McCall3b657512011-01-19 10:06:00 +00002388 // If we don't have one, build one.
2389 if (!canonTy) {
2390 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002391 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002392 QualType(), numElements, ASM, elementTypeQuals,
2393 brackets);
2394 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2395 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002396 }
2397
John McCall3b657512011-01-19 10:06:00 +00002398 // Apply qualifiers from the element type to the array.
2399 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002400 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002401
John McCall3b657512011-01-19 10:06:00 +00002402 // If we didn't need extra canonicalization for the element type,
2403 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002404 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002405 return canon;
2406
2407 // Otherwise, we need to build a type which follows the spelling
2408 // of the element type.
2409 DependentSizedArrayType *sugaredType
2410 = new (*this, TypeAlignment)
2411 DependentSizedArrayType(*this, elementType, canon, numElements,
2412 ASM, elementTypeQuals, brackets);
2413 Types.push_back(sugaredType);
2414 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002415}
2416
John McCall3b657512011-01-19 10:06:00 +00002417QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002418 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002419 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002420 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002421 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002422
John McCall3b657512011-01-19 10:06:00 +00002423 void *insertPos = 0;
2424 if (IncompleteArrayType *iat =
2425 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2426 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002427
2428 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002429 // either, so fill in the canonical type field. We also have to pull
2430 // qualifiers off the element type.
2431 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002432
John McCall3b657512011-01-19 10:06:00 +00002433 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2434 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002435 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002436 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002437 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002438
2439 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002440 IncompleteArrayType *existing =
2441 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2442 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002443 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002444
John McCall3b657512011-01-19 10:06:00 +00002445 IncompleteArrayType *newType = new (*this, TypeAlignment)
2446 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002447
John McCall3b657512011-01-19 10:06:00 +00002448 IncompleteArrayTypes.InsertNode(newType, insertPos);
2449 Types.push_back(newType);
2450 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002451}
2452
Steve Naroff73322922007-07-18 18:00:27 +00002453/// getVectorType - Return the unique reference to a vector type of
2454/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002455QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002456 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002457 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002458
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 // Check if we've already instantiated a vector of this type.
2460 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002461 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002462
Reid Spencer5f016e22007-07-11 17:01:13 +00002463 void *InsertPos = 0;
2464 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2465 return QualType(VTP, 0);
2466
2467 // If the element type isn't canonical, this won't be a canonical type either,
2468 // so fill in the canonical type field.
2469 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002470 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002471 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Reid Spencer5f016e22007-07-11 17:01:13 +00002473 // Get the new insert position for the node we care about.
2474 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002475 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 }
John McCall6b304a02009-09-24 23:30:46 +00002477 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002478 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 VectorTypes.InsertNode(New, InsertPos);
2480 Types.push_back(New);
2481 return QualType(New, 0);
2482}
2483
Nate Begeman213541a2008-04-18 23:10:10 +00002484/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002485/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002486QualType
2487ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002488 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Steve Naroff73322922007-07-18 18:00:27 +00002490 // Check if we've already instantiated a vector of this type.
2491 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002492 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002493 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002494 void *InsertPos = 0;
2495 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2496 return QualType(VTP, 0);
2497
2498 // If the element type isn't canonical, this won't be a canonical type either,
2499 // so fill in the canonical type field.
2500 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002501 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002502 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Steve Naroff73322922007-07-18 18:00:27 +00002504 // Get the new insert position for the node we care about.
2505 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002506 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002507 }
John McCall6b304a02009-09-24 23:30:46 +00002508 ExtVectorType *New = new (*this, TypeAlignment)
2509 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002510 VectorTypes.InsertNode(New, InsertPos);
2511 Types.push_back(New);
2512 return QualType(New, 0);
2513}
2514
Jay Foad4ba2a172011-01-12 09:06:06 +00002515QualType
2516ASTContext::getDependentSizedExtVectorType(QualType vecType,
2517 Expr *SizeExpr,
2518 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002519 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002520 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002521 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002523 void *InsertPos = 0;
2524 DependentSizedExtVectorType *Canon
2525 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2526 DependentSizedExtVectorType *New;
2527 if (Canon) {
2528 // We already have a canonical version of this array type; use it as
2529 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002530 New = new (*this, TypeAlignment)
2531 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2532 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002533 } else {
2534 QualType CanonVecTy = getCanonicalType(vecType);
2535 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002536 New = new (*this, TypeAlignment)
2537 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2538 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002539
2540 DependentSizedExtVectorType *CanonCheck
2541 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2542 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2543 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002544 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2545 } else {
2546 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2547 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002548 New = new (*this, TypeAlignment)
2549 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002550 }
2551 }
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002553 Types.push_back(New);
2554 return QualType(New, 0);
2555}
2556
Douglas Gregor72564e72009-02-26 23:50:07 +00002557/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002558///
Jay Foad4ba2a172011-01-12 09:06:06 +00002559QualType
2560ASTContext::getFunctionNoProtoType(QualType ResultTy,
2561 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002562 const CallingConv DefaultCC = Info.getCC();
2563 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2564 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 // Unique functions, to guarantee there is only one function of a particular
2566 // structure.
2567 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002568 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002569
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002571 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002572 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002576 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002577 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002578 Canonical =
2579 getFunctionNoProtoType(getCanonicalType(ResultTy),
2580 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002583 FunctionNoProtoType *NewIP =
2584 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002585 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 }
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Roman Divackycfe9af22011-03-01 17:40:53 +00002588 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002589 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002590 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002592 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 return QualType(New, 0);
2594}
2595
2596/// getFunctionType - Return a normal function type with a typed argument
2597/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002598QualType
2599ASTContext::getFunctionType(QualType ResultTy,
2600 const QualType *ArgArray, unsigned NumArgs,
2601 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 // Unique functions, to guarantee there is only one function of a particular
2603 // structure.
2604 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002605 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002606
2607 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002608 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002609 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002611
2612 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002613 bool isCanonical =
2614 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2615 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002617 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 isCanonical = false;
2619
Roman Divackycfe9af22011-03-01 17:40:53 +00002620 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2621 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2622 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002623
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002625 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002627 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002628 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 CanonicalArgs.reserve(NumArgs);
2630 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002631 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002632
John McCalle23cf432010-12-14 08:05:40 +00002633 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002634 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002635 CanonicalEPI.ExceptionSpecType = EST_None;
2636 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002637 CanonicalEPI.ExtInfo
2638 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2639
Chris Lattnerf52ab252008-04-06 22:59:24 +00002640 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002641 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002642 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002643
Reid Spencer5f016e22007-07-11 17:01:13 +00002644 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002645 FunctionProtoType *NewIP =
2646 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002647 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002649
John McCallf85e1932011-06-15 23:02:42 +00002650 // FunctionProtoType objects are allocated with extra bytes after
2651 // them for three variable size arrays at the end:
2652 // - parameter types
2653 // - exception types
2654 // - consumed-arguments flags
2655 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002656 // expression, or information used to resolve the exception
2657 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002658 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002659 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002660 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002661 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002662 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002663 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002664 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002665 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002666 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2667 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002668 }
John McCallf85e1932011-06-15 23:02:42 +00002669 if (EPI.ConsumedArguments)
2670 Size += NumArgs * sizeof(bool);
2671
John McCalle23cf432010-12-14 08:05:40 +00002672 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002673 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2674 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002675 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002677 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 return QualType(FTP, 0);
2679}
2680
John McCall3cb0ebd2010-03-10 03:28:59 +00002681#ifndef NDEBUG
2682static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2683 if (!isa<CXXRecordDecl>(D)) return false;
2684 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2685 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2686 return true;
2687 if (RD->getDescribedClassTemplate() &&
2688 !isa<ClassTemplateSpecializationDecl>(RD))
2689 return true;
2690 return false;
2691}
2692#endif
2693
2694/// getInjectedClassNameType - Return the unique reference to the
2695/// injected class name type for the specified templated declaration.
2696QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002697 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002698 assert(NeedsInjectedClassNameType(Decl));
2699 if (Decl->TypeForDecl) {
2700 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002701 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002702 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2703 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2704 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2705 } else {
John McCallf4c73712011-01-19 06:33:43 +00002706 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002707 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002708 Decl->TypeForDecl = newType;
2709 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002710 }
2711 return QualType(Decl->TypeForDecl, 0);
2712}
2713
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002714/// getTypeDeclType - Return the unique reference to the type for the
2715/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002716QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002717 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002718 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Richard Smith162e1c12011-04-15 14:24:37 +00002720 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002721 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002722
John McCallbecb8d52010-03-10 06:48:02 +00002723 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2724 "Template type parameter types are always available.");
2725
John McCall19c85762010-02-16 03:57:14 +00002726 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002727 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002728 "struct/union has previous declaration");
2729 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002730 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002731 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002732 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002733 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002734 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002735 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002736 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002737 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2738 Decl->TypeForDecl = newType;
2739 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002740 } else
John McCallbecb8d52010-03-10 06:48:02 +00002741 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002742
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002743 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002744}
2745
Reid Spencer5f016e22007-07-11 17:01:13 +00002746/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002747/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002748QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002749ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2750 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002753 if (Canonical.isNull())
2754 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002755 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002756 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002757 Decl->TypeForDecl = newType;
2758 Types.push_back(newType);
2759 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002760}
2761
Jay Foad4ba2a172011-01-12 09:06:06 +00002762QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002763 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2764
Douglas Gregoref96ee02012-01-14 16:38:05 +00002765 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002766 if (PrevDecl->TypeForDecl)
2767 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2768
John McCallf4c73712011-01-19 06:33:43 +00002769 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2770 Decl->TypeForDecl = newType;
2771 Types.push_back(newType);
2772 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002773}
2774
Jay Foad4ba2a172011-01-12 09:06:06 +00002775QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002776 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2777
Douglas Gregoref96ee02012-01-14 16:38:05 +00002778 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002779 if (PrevDecl->TypeForDecl)
2780 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2781
John McCallf4c73712011-01-19 06:33:43 +00002782 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2783 Decl->TypeForDecl = newType;
2784 Types.push_back(newType);
2785 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002786}
2787
John McCall9d156a72011-01-06 01:58:22 +00002788QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2789 QualType modifiedType,
2790 QualType equivalentType) {
2791 llvm::FoldingSetNodeID id;
2792 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2793
2794 void *insertPos = 0;
2795 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2796 if (type) return QualType(type, 0);
2797
2798 QualType canon = getCanonicalType(equivalentType);
2799 type = new (*this, TypeAlignment)
2800 AttributedType(canon, attrKind, modifiedType, equivalentType);
2801
2802 Types.push_back(type);
2803 AttributedTypes.InsertNode(type, insertPos);
2804
2805 return QualType(type, 0);
2806}
2807
2808
John McCall49a832b2009-10-18 09:09:24 +00002809/// \brief Retrieve a substitution-result type.
2810QualType
2811ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002812 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002813 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002814 && "replacement types must always be canonical");
2815
2816 llvm::FoldingSetNodeID ID;
2817 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2818 void *InsertPos = 0;
2819 SubstTemplateTypeParmType *SubstParm
2820 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2821
2822 if (!SubstParm) {
2823 SubstParm = new (*this, TypeAlignment)
2824 SubstTemplateTypeParmType(Parm, Replacement);
2825 Types.push_back(SubstParm);
2826 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2827 }
2828
2829 return QualType(SubstParm, 0);
2830}
2831
Douglas Gregorc3069d62011-01-14 02:55:32 +00002832/// \brief Retrieve a
2833QualType ASTContext::getSubstTemplateTypeParmPackType(
2834 const TemplateTypeParmType *Parm,
2835 const TemplateArgument &ArgPack) {
2836#ifndef NDEBUG
2837 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2838 PEnd = ArgPack.pack_end();
2839 P != PEnd; ++P) {
2840 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2841 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2842 }
2843#endif
2844
2845 llvm::FoldingSetNodeID ID;
2846 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2847 void *InsertPos = 0;
2848 if (SubstTemplateTypeParmPackType *SubstParm
2849 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2850 return QualType(SubstParm, 0);
2851
2852 QualType Canon;
2853 if (!Parm->isCanonicalUnqualified()) {
2854 Canon = getCanonicalType(QualType(Parm, 0));
2855 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2856 ArgPack);
2857 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2858 }
2859
2860 SubstTemplateTypeParmPackType *SubstParm
2861 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2862 ArgPack);
2863 Types.push_back(SubstParm);
2864 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2865 return QualType(SubstParm, 0);
2866}
2867
Douglas Gregorfab9d672009-02-05 23:33:38 +00002868/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002869/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002870/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002871QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002872 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002873 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002874 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002875 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002876 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002877 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002878 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2879
2880 if (TypeParm)
2881 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002883 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002884 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002885 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002886
2887 TemplateTypeParmType *TypeCheck
2888 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2889 assert(!TypeCheck && "Template type parameter canonical type broken");
2890 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002891 } else
John McCall6b304a02009-09-24 23:30:46 +00002892 TypeParm = new (*this, TypeAlignment)
2893 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002894
2895 Types.push_back(TypeParm);
2896 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2897
2898 return QualType(TypeParm, 0);
2899}
2900
John McCall3cb0ebd2010-03-10 03:28:59 +00002901TypeSourceInfo *
2902ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2903 SourceLocation NameLoc,
2904 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002905 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002906 assert(!Name.getAsDependentTemplateName() &&
2907 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002908 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002909
2910 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2911 TemplateSpecializationTypeLoc TL
2912 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002913 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002914 TL.setTemplateNameLoc(NameLoc);
2915 TL.setLAngleLoc(Args.getLAngleLoc());
2916 TL.setRAngleLoc(Args.getRAngleLoc());
2917 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2918 TL.setArgLocInfo(i, Args[i].getLocInfo());
2919 return DI;
2920}
2921
Mike Stump1eb44332009-09-09 15:08:12 +00002922QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002923ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002924 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002925 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002926 assert(!Template.getAsDependentTemplateName() &&
2927 "No dependent template names here!");
2928
John McCalld5532b62009-11-23 01:53:49 +00002929 unsigned NumArgs = Args.size();
2930
Chris Lattner5f9e2722011-07-23 10:55:15 +00002931 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002932 ArgVec.reserve(NumArgs);
2933 for (unsigned i = 0; i != NumArgs; ++i)
2934 ArgVec.push_back(Args[i].getArgument());
2935
John McCall31f17ec2010-04-27 00:57:59 +00002936 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002937 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002938}
2939
Douglas Gregorb70126a2012-02-03 17:16:23 +00002940#ifndef NDEBUG
2941static bool hasAnyPackExpansions(const TemplateArgument *Args,
2942 unsigned NumArgs) {
2943 for (unsigned I = 0; I != NumArgs; ++I)
2944 if (Args[I].isPackExpansion())
2945 return true;
2946
2947 return true;
2948}
2949#endif
2950
John McCall833ca992009-10-29 08:12:44 +00002951QualType
2952ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002953 const TemplateArgument *Args,
2954 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002955 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002956 assert(!Template.getAsDependentTemplateName() &&
2957 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002958 // Look through qualified template names.
2959 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2960 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002961
Douglas Gregorb70126a2012-02-03 17:16:23 +00002962 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002963 Template.getAsTemplateDecl() &&
2964 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002965 QualType CanonType;
2966 if (!Underlying.isNull())
2967 CanonType = getCanonicalType(Underlying);
2968 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002969 // We can get here with an alias template when the specialization contains
2970 // a pack expansion that does not match up with a parameter pack.
2971 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2972 "Caller must compute aliased type");
2973 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002974 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2975 NumArgs);
2976 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002977
Douglas Gregor1275ae02009-07-28 23:00:59 +00002978 // Allocate the (non-canonical) template specialization type, but don't
2979 // try to unique it: these types typically have location information that
2980 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002981 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2982 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002983 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002984 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002985 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002986 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2987 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002988
Douglas Gregor55f6b142009-02-09 18:46:07 +00002989 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002990 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002991}
2992
Mike Stump1eb44332009-09-09 15:08:12 +00002993QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002994ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2995 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002996 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002997 assert(!Template.getAsDependentTemplateName() &&
2998 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002999
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003000 // Look through qualified template names.
3001 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3002 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003003
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003004 // Build the canonical template specialization type.
3005 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003006 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003007 CanonArgs.reserve(NumArgs);
3008 for (unsigned I = 0; I != NumArgs; ++I)
3009 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3010
3011 // Determine whether this canonical template specialization type already
3012 // exists.
3013 llvm::FoldingSetNodeID ID;
3014 TemplateSpecializationType::Profile(ID, CanonTemplate,
3015 CanonArgs.data(), NumArgs, *this);
3016
3017 void *InsertPos = 0;
3018 TemplateSpecializationType *Spec
3019 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3020
3021 if (!Spec) {
3022 // Allocate a new canonical template specialization type.
3023 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3024 sizeof(TemplateArgument) * NumArgs),
3025 TypeAlignment);
3026 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3027 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003028 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003029 Types.push_back(Spec);
3030 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3031 }
3032
3033 assert(Spec->isDependentType() &&
3034 "Non-dependent template-id type must have a canonical type");
3035 return QualType(Spec, 0);
3036}
3037
3038QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003039ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3040 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003041 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003042 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003043 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003044
3045 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003046 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003047 if (T)
3048 return QualType(T, 0);
3049
Douglas Gregor789b1f62010-02-04 18:10:26 +00003050 QualType Canon = NamedType;
3051 if (!Canon.isCanonical()) {
3052 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003053 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3054 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003055 (void)CheckT;
3056 }
3057
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003058 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003059 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003060 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003061 return QualType(T, 0);
3062}
3063
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003064QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003065ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003066 llvm::FoldingSetNodeID ID;
3067 ParenType::Profile(ID, InnerType);
3068
3069 void *InsertPos = 0;
3070 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3071 if (T)
3072 return QualType(T, 0);
3073
3074 QualType Canon = InnerType;
3075 if (!Canon.isCanonical()) {
3076 Canon = getCanonicalType(InnerType);
3077 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3078 assert(!CheckT && "Paren canonical type broken");
3079 (void)CheckT;
3080 }
3081
3082 T = new (*this) ParenType(InnerType, Canon);
3083 Types.push_back(T);
3084 ParenTypes.InsertNode(T, InsertPos);
3085 return QualType(T, 0);
3086}
3087
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003088QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3089 NestedNameSpecifier *NNS,
3090 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003091 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003092 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3093
3094 if (Canon.isNull()) {
3095 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003096 ElaboratedTypeKeyword CanonKeyword = Keyword;
3097 if (Keyword == ETK_None)
3098 CanonKeyword = ETK_Typename;
3099
3100 if (CanonNNS != NNS || CanonKeyword != Keyword)
3101 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003102 }
3103
3104 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003105 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003106
3107 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003108 DependentNameType *T
3109 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003110 if (T)
3111 return QualType(T, 0);
3112
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003113 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003114 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003115 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003116 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003117}
3118
Mike Stump1eb44332009-09-09 15:08:12 +00003119QualType
John McCall33500952010-06-11 00:33:02 +00003120ASTContext::getDependentTemplateSpecializationType(
3121 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003122 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003123 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003124 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003125 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003126 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003127 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3128 ArgCopy.push_back(Args[I].getArgument());
3129 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3130 ArgCopy.size(),
3131 ArgCopy.data());
3132}
3133
3134QualType
3135ASTContext::getDependentTemplateSpecializationType(
3136 ElaboratedTypeKeyword Keyword,
3137 NestedNameSpecifier *NNS,
3138 const IdentifierInfo *Name,
3139 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003140 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003141 assert((!NNS || NNS->isDependent()) &&
3142 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003143
Douglas Gregor789b1f62010-02-04 18:10:26 +00003144 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003145 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3146 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003147
3148 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003149 DependentTemplateSpecializationType *T
3150 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003151 if (T)
3152 return QualType(T, 0);
3153
John McCall33500952010-06-11 00:33:02 +00003154 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003155
John McCall33500952010-06-11 00:33:02 +00003156 ElaboratedTypeKeyword CanonKeyword = Keyword;
3157 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3158
3159 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003160 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003161 for (unsigned I = 0; I != NumArgs; ++I) {
3162 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3163 if (!CanonArgs[I].structurallyEquals(Args[I]))
3164 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003165 }
3166
John McCall33500952010-06-11 00:33:02 +00003167 QualType Canon;
3168 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3169 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3170 Name, NumArgs,
3171 CanonArgs.data());
3172
3173 // Find the insert position again.
3174 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3175 }
3176
3177 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3178 sizeof(TemplateArgument) * NumArgs),
3179 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003180 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003181 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003182 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003183 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003184 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003185}
3186
Douglas Gregorcded4f62011-01-14 17:04:44 +00003187QualType ASTContext::getPackExpansionType(QualType Pattern,
3188 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003189 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003190 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003191
3192 assert(Pattern->containsUnexpandedParameterPack() &&
3193 "Pack expansions must expand one or more parameter packs");
3194 void *InsertPos = 0;
3195 PackExpansionType *T
3196 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3197 if (T)
3198 return QualType(T, 0);
3199
3200 QualType Canon;
3201 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003202 Canon = getCanonicalType(Pattern);
3203 // The canonical type might not contain an unexpanded parameter pack, if it
3204 // contains an alias template specialization which ignores one of its
3205 // parameters.
3206 if (Canon->containsUnexpandedParameterPack()) {
3207 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003208
Richard Smithd8672ef2012-07-16 00:20:35 +00003209 // Find the insert position again, in case we inserted an element into
3210 // PackExpansionTypes and invalidated our insert position.
3211 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3212 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003213 }
3214
Douglas Gregorcded4f62011-01-14 17:04:44 +00003215 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003216 Types.push_back(T);
3217 PackExpansionTypes.InsertNode(T, InsertPos);
3218 return QualType(T, 0);
3219}
3220
Chris Lattner88cb27a2008-04-07 04:56:42 +00003221/// CmpProtocolNames - Comparison predicate for sorting protocols
3222/// alphabetically.
3223static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3224 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003225 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003226}
3227
John McCallc12c5bb2010-05-15 11:32:37 +00003228static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003229 unsigned NumProtocols) {
3230 if (NumProtocols == 0) return true;
3231
Douglas Gregor61cc2962012-01-02 02:00:30 +00003232 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3233 return false;
3234
John McCall54e14c42009-10-22 22:37:11 +00003235 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003236 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3237 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003238 return false;
3239 return true;
3240}
3241
3242static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003243 unsigned &NumProtocols) {
3244 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Chris Lattner88cb27a2008-04-07 04:56:42 +00003246 // Sort protocols, keyed by name.
3247 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3248
Douglas Gregor61cc2962012-01-02 02:00:30 +00003249 // Canonicalize.
3250 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3251 Protocols[I] = Protocols[I]->getCanonicalDecl();
3252
Chris Lattner88cb27a2008-04-07 04:56:42 +00003253 // Remove duplicates.
3254 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3255 NumProtocols = ProtocolsEnd-Protocols;
3256}
3257
John McCallc12c5bb2010-05-15 11:32:37 +00003258QualType ASTContext::getObjCObjectType(QualType BaseType,
3259 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003260 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003261 // If the base type is an interface and there aren't any protocols
3262 // to add, then the interface type will do just fine.
3263 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3264 return BaseType;
3265
3266 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003267 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003268 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003269 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003270 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3271 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003272
John McCallc12c5bb2010-05-15 11:32:37 +00003273 // Build the canonical type, which has the canonical base type and
3274 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003275 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003276 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3277 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3278 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003279 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003280 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003281 unsigned UniqueCount = NumProtocols;
3282
John McCall54e14c42009-10-22 22:37:11 +00003283 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003284 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3285 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003286 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003287 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3288 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003289 }
3290
3291 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003292 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3293 }
3294
3295 unsigned Size = sizeof(ObjCObjectTypeImpl);
3296 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3297 void *Mem = Allocate(Size, TypeAlignment);
3298 ObjCObjectTypeImpl *T =
3299 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3300
3301 Types.push_back(T);
3302 ObjCObjectTypes.InsertNode(T, InsertPos);
3303 return QualType(T, 0);
3304}
3305
3306/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3307/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003308QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003309 llvm::FoldingSetNodeID ID;
3310 ObjCObjectPointerType::Profile(ID, ObjectT);
3311
3312 void *InsertPos = 0;
3313 if (ObjCObjectPointerType *QT =
3314 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3315 return QualType(QT, 0);
3316
3317 // Find the canonical object type.
3318 QualType Canonical;
3319 if (!ObjectT.isCanonical()) {
3320 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3321
3322 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003323 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3324 }
3325
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003326 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003327 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3328 ObjCObjectPointerType *QType =
3329 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003330
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003331 Types.push_back(QType);
3332 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003333 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003334}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003335
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003336/// getObjCInterfaceType - Return the unique reference to the type for the
3337/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003338QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3339 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003340 if (Decl->TypeForDecl)
3341 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003342
Douglas Gregor0af55012011-12-16 03:12:41 +00003343 if (PrevDecl) {
3344 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3345 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3346 return QualType(PrevDecl->TypeForDecl, 0);
3347 }
3348
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003349 // Prefer the definition, if there is one.
3350 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3351 Decl = Def;
3352
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003353 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3354 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3355 Decl->TypeForDecl = T;
3356 Types.push_back(T);
3357 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003358}
3359
Douglas Gregor72564e72009-02-26 23:50:07 +00003360/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3361/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003362/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003363/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003364/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003365QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003366 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003367 if (tofExpr->isTypeDependent()) {
3368 llvm::FoldingSetNodeID ID;
3369 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003370
Douglas Gregorb1975722009-07-30 23:18:24 +00003371 void *InsertPos = 0;
3372 DependentTypeOfExprType *Canon
3373 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3374 if (Canon) {
3375 // We already have a "canonical" version of an identical, dependent
3376 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003377 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003378 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003379 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003380 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003381 Canon
3382 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003383 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3384 toe = Canon;
3385 }
3386 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003387 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003388 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003389 }
Steve Naroff9752f252007-08-01 18:02:17 +00003390 Types.push_back(toe);
3391 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003392}
3393
Steve Naroff9752f252007-08-01 18:02:17 +00003394/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3395/// TypeOfType AST's. The only motivation to unique these nodes would be
3396/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003397/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003398/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003399QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003400 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003401 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003402 Types.push_back(tot);
3403 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003404}
3405
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003406
Anders Carlsson395b4752009-06-24 19:06:50 +00003407/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3408/// DecltypeType AST's. The only motivation to unique these nodes would be
3409/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003410/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003411/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003412QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003413 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003414
3415 // C++0x [temp.type]p2:
3416 // If an expression e involves a template parameter, decltype(e) denotes a
3417 // unique dependent type. Two such decltype-specifiers refer to the same
3418 // type only if their expressions are equivalent (14.5.6.1).
3419 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003420 llvm::FoldingSetNodeID ID;
3421 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003422
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003423 void *InsertPos = 0;
3424 DependentDecltypeType *Canon
3425 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3426 if (Canon) {
3427 // We already have a "canonical" version of an equivalent, dependent
3428 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003429 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003430 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003431 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003432 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003433 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003434 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3435 dt = Canon;
3436 }
3437 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003438 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3439 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003440 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003441 Types.push_back(dt);
3442 return QualType(dt, 0);
3443}
3444
Sean Huntca63c202011-05-24 22:41:36 +00003445/// getUnaryTransformationType - We don't unique these, since the memory
3446/// savings are minimal and these are rare.
3447QualType ASTContext::getUnaryTransformType(QualType BaseType,
3448 QualType UnderlyingType,
3449 UnaryTransformType::UTTKind Kind)
3450 const {
3451 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003452 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3453 Kind,
3454 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003455 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003456 Types.push_back(Ty);
3457 return QualType(Ty, 0);
3458}
3459
Richard Smith483b9f32011-02-21 20:05:19 +00003460/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003461QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003462 void *InsertPos = 0;
3463 if (!DeducedType.isNull()) {
3464 // Look in the folding set for an existing type.
3465 llvm::FoldingSetNodeID ID;
3466 AutoType::Profile(ID, DeducedType);
3467 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3468 return QualType(AT, 0);
3469 }
3470
3471 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3472 Types.push_back(AT);
3473 if (InsertPos)
3474 AutoTypes.InsertNode(AT, InsertPos);
3475 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003476}
3477
Eli Friedmanb001de72011-10-06 23:00:33 +00003478/// getAtomicType - Return the uniqued reference to the atomic type for
3479/// the given value type.
3480QualType ASTContext::getAtomicType(QualType T) const {
3481 // Unique pointers, to guarantee there is only one pointer of a particular
3482 // structure.
3483 llvm::FoldingSetNodeID ID;
3484 AtomicType::Profile(ID, T);
3485
3486 void *InsertPos = 0;
3487 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3488 return QualType(AT, 0);
3489
3490 // If the atomic value type isn't canonical, this won't be a canonical type
3491 // either, so fill in the canonical type field.
3492 QualType Canonical;
3493 if (!T.isCanonical()) {
3494 Canonical = getAtomicType(getCanonicalType(T));
3495
3496 // Get the new insert position for the node we care about.
3497 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3498 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3499 }
3500 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3501 Types.push_back(New);
3502 AtomicTypes.InsertNode(New, InsertPos);
3503 return QualType(New, 0);
3504}
3505
Richard Smithad762fc2011-04-14 22:09:26 +00003506/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3507QualType ASTContext::getAutoDeductType() const {
3508 if (AutoDeductTy.isNull())
3509 AutoDeductTy = getAutoType(QualType());
3510 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3511 return AutoDeductTy;
3512}
3513
3514/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3515QualType ASTContext::getAutoRRefDeductType() const {
3516 if (AutoRRefDeductTy.isNull())
3517 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3518 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3519 return AutoRRefDeductTy;
3520}
3521
Reid Spencer5f016e22007-07-11 17:01:13 +00003522/// getTagDeclType - Return the unique reference to the type for the
3523/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003524QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003525 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003526 // FIXME: What is the design on getTagDeclType when it requires casting
3527 // away const? mutable?
3528 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003529}
3530
Mike Stump1eb44332009-09-09 15:08:12 +00003531/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3532/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3533/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003534CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003535 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003536}
3537
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003538/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3539CanQualType ASTContext::getIntMaxType() const {
3540 return getFromTargetType(Target->getIntMaxType());
3541}
3542
3543/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3544CanQualType ASTContext::getUIntMaxType() const {
3545 return getFromTargetType(Target->getUIntMaxType());
3546}
3547
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003548/// getSignedWCharType - Return the type of "signed wchar_t".
3549/// Used when in C++, as a GCC extension.
3550QualType ASTContext::getSignedWCharType() const {
3551 // FIXME: derive from "Target" ?
3552 return WCharTy;
3553}
3554
3555/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3556/// Used when in C++, as a GCC extension.
3557QualType ASTContext::getUnsignedWCharType() const {
3558 // FIXME: derive from "Target" ?
3559 return UnsignedIntTy;
3560}
3561
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003562/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003563/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3564QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003565 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003566}
3567
Eli Friedman6902e412012-11-27 02:58:24 +00003568/// \brief Return the unique type for "pid_t" defined in
3569/// <sys/types.h>. We need this to compute the correct type for vfork().
3570QualType ASTContext::getProcessIDType() const {
3571 return getFromTargetType(Target->getProcessIDType());
3572}
3573
Chris Lattnere6327742008-04-02 05:18:44 +00003574//===----------------------------------------------------------------------===//
3575// Type Operators
3576//===----------------------------------------------------------------------===//
3577
Jay Foad4ba2a172011-01-12 09:06:06 +00003578CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003579 // Push qualifiers into arrays, and then discard any remaining
3580 // qualifiers.
3581 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003582 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003583 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003584 QualType Result;
3585 if (isa<ArrayType>(Ty)) {
3586 Result = getArrayDecayedType(QualType(Ty,0));
3587 } else if (isa<FunctionType>(Ty)) {
3588 Result = getPointerType(QualType(Ty, 0));
3589 } else {
3590 Result = QualType(Ty, 0);
3591 }
3592
3593 return CanQualType::CreateUnsafe(Result);
3594}
3595
John McCall62c28c82011-01-18 07:41:22 +00003596QualType ASTContext::getUnqualifiedArrayType(QualType type,
3597 Qualifiers &quals) {
3598 SplitQualType splitType = type.getSplitUnqualifiedType();
3599
3600 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3601 // the unqualified desugared type and then drops it on the floor.
3602 // We then have to strip that sugar back off with
3603 // getUnqualifiedDesugaredType(), which is silly.
3604 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003605 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003606
3607 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003608 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003609 quals = splitType.Quals;
3610 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003611 }
3612
John McCall62c28c82011-01-18 07:41:22 +00003613 // Otherwise, recurse on the array's element type.
3614 QualType elementType = AT->getElementType();
3615 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3616
3617 // If that didn't change the element type, AT has no qualifiers, so we
3618 // can just use the results in splitType.
3619 if (elementType == unqualElementType) {
3620 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003621 quals = splitType.Quals;
3622 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003623 }
3624
3625 // Otherwise, add in the qualifiers from the outermost type, then
3626 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003627 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003628
Douglas Gregor9dadd942010-05-17 18:45:21 +00003629 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003630 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003631 CAT->getSizeModifier(), 0);
3632 }
3633
Douglas Gregor9dadd942010-05-17 18:45:21 +00003634 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003635 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003636 }
3637
Douglas Gregor9dadd942010-05-17 18:45:21 +00003638 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003639 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003640 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003641 VAT->getSizeModifier(),
3642 VAT->getIndexTypeCVRQualifiers(),
3643 VAT->getBracketsRange());
3644 }
3645
3646 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003647 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003648 DSAT->getSizeModifier(), 0,
3649 SourceRange());
3650}
3651
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003652/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3653/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3654/// they point to and return true. If T1 and T2 aren't pointer types
3655/// or pointer-to-member types, or if they are not similar at this
3656/// level, returns false and leaves T1 and T2 unchanged. Top-level
3657/// qualifiers on T1 and T2 are ignored. This function will typically
3658/// be called in a loop that successively "unwraps" pointer and
3659/// pointer-to-member types to compare them at each level.
3660bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3661 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3662 *T2PtrType = T2->getAs<PointerType>();
3663 if (T1PtrType && T2PtrType) {
3664 T1 = T1PtrType->getPointeeType();
3665 T2 = T2PtrType->getPointeeType();
3666 return true;
3667 }
3668
3669 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3670 *T2MPType = T2->getAs<MemberPointerType>();
3671 if (T1MPType && T2MPType &&
3672 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3673 QualType(T2MPType->getClass(), 0))) {
3674 T1 = T1MPType->getPointeeType();
3675 T2 = T2MPType->getPointeeType();
3676 return true;
3677 }
3678
David Blaikie4e4d0842012-03-11 07:00:24 +00003679 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003680 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3681 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3682 if (T1OPType && T2OPType) {
3683 T1 = T1OPType->getPointeeType();
3684 T2 = T2OPType->getPointeeType();
3685 return true;
3686 }
3687 }
3688
3689 // FIXME: Block pointers, too?
3690
3691 return false;
3692}
3693
Jay Foad4ba2a172011-01-12 09:06:06 +00003694DeclarationNameInfo
3695ASTContext::getNameForTemplate(TemplateName Name,
3696 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003697 switch (Name.getKind()) {
3698 case TemplateName::QualifiedTemplate:
3699 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003700 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003701 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3702 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003703
John McCall14606042011-06-30 08:33:18 +00003704 case TemplateName::OverloadedTemplate: {
3705 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3706 // DNInfo work in progress: CHECKME: what about DNLoc?
3707 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3708 }
3709
3710 case TemplateName::DependentTemplate: {
3711 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003712 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003713 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003714 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3715 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003716 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003717 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3718 // DNInfo work in progress: FIXME: source locations?
3719 DeclarationNameLoc DNLoc;
3720 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3721 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3722 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003723 }
3724 }
3725
John McCall14606042011-06-30 08:33:18 +00003726 case TemplateName::SubstTemplateTemplateParm: {
3727 SubstTemplateTemplateParmStorage *subst
3728 = Name.getAsSubstTemplateTemplateParm();
3729 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3730 NameLoc);
3731 }
3732
3733 case TemplateName::SubstTemplateTemplateParmPack: {
3734 SubstTemplateTemplateParmPackStorage *subst
3735 = Name.getAsSubstTemplateTemplateParmPack();
3736 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3737 NameLoc);
3738 }
3739 }
3740
3741 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003742}
3743
Jay Foad4ba2a172011-01-12 09:06:06 +00003744TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003745 switch (Name.getKind()) {
3746 case TemplateName::QualifiedTemplate:
3747 case TemplateName::Template: {
3748 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003749 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003750 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003751 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3752
3753 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003754 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003755 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003756
John McCall14606042011-06-30 08:33:18 +00003757 case TemplateName::OverloadedTemplate:
3758 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003759
John McCall14606042011-06-30 08:33:18 +00003760 case TemplateName::DependentTemplate: {
3761 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3762 assert(DTN && "Non-dependent template names must refer to template decls.");
3763 return DTN->CanonicalTemplateName;
3764 }
3765
3766 case TemplateName::SubstTemplateTemplateParm: {
3767 SubstTemplateTemplateParmStorage *subst
3768 = Name.getAsSubstTemplateTemplateParm();
3769 return getCanonicalTemplateName(subst->getReplacement());
3770 }
3771
3772 case TemplateName::SubstTemplateTemplateParmPack: {
3773 SubstTemplateTemplateParmPackStorage *subst
3774 = Name.getAsSubstTemplateTemplateParmPack();
3775 TemplateTemplateParmDecl *canonParameter
3776 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3777 TemplateArgument canonArgPack
3778 = getCanonicalTemplateArgument(subst->getArgumentPack());
3779 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3780 }
3781 }
3782
3783 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003784}
3785
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003786bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3787 X = getCanonicalTemplateName(X);
3788 Y = getCanonicalTemplateName(Y);
3789 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3790}
3791
Mike Stump1eb44332009-09-09 15:08:12 +00003792TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003793ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003794 switch (Arg.getKind()) {
3795 case TemplateArgument::Null:
3796 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Douglas Gregor1275ae02009-07-28 23:00:59 +00003798 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003799 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Douglas Gregord2008e22012-04-06 22:40:38 +00003801 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003802 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3803 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003804 }
Mike Stump1eb44332009-09-09 15:08:12 +00003805
Eli Friedmand7a6b162012-09-26 02:36:12 +00003806 case TemplateArgument::NullPtr:
3807 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3808 /*isNullPtr*/true);
3809
Douglas Gregor788cd062009-11-11 01:00:40 +00003810 case TemplateArgument::Template:
3811 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003812
3813 case TemplateArgument::TemplateExpansion:
3814 return TemplateArgument(getCanonicalTemplateName(
3815 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003816 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003817
Douglas Gregor1275ae02009-07-28 23:00:59 +00003818 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003819 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003820
Douglas Gregor1275ae02009-07-28 23:00:59 +00003821 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003822 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003823
Douglas Gregor1275ae02009-07-28 23:00:59 +00003824 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003825 if (Arg.pack_size() == 0)
3826 return Arg;
3827
Douglas Gregor910f8002010-11-07 23:05:16 +00003828 TemplateArgument *CanonArgs
3829 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003830 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003831 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003832 AEnd = Arg.pack_end();
3833 A != AEnd; (void)++A, ++Idx)
3834 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Douglas Gregor910f8002010-11-07 23:05:16 +00003836 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003837 }
3838 }
3839
3840 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003841 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003842}
3843
Douglas Gregord57959a2009-03-27 23:10:48 +00003844NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003845ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003846 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003847 return 0;
3848
3849 switch (NNS->getKind()) {
3850 case NestedNameSpecifier::Identifier:
3851 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003852 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003853 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3854 NNS->getAsIdentifier());
3855
3856 case NestedNameSpecifier::Namespace:
3857 // A namespace is canonical; build a nested-name-specifier with
3858 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003859 return NestedNameSpecifier::Create(*this, 0,
3860 NNS->getAsNamespace()->getOriginalNamespace());
3861
3862 case NestedNameSpecifier::NamespaceAlias:
3863 // A namespace is canonical; build a nested-name-specifier with
3864 // this namespace and no prefix.
3865 return NestedNameSpecifier::Create(*this, 0,
3866 NNS->getAsNamespaceAlias()->getNamespace()
3867 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003868
3869 case NestedNameSpecifier::TypeSpec:
3870 case NestedNameSpecifier::TypeSpecWithTemplate: {
3871 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003872
3873 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3874 // break it apart into its prefix and identifier, then reconsititute those
3875 // as the canonical nested-name-specifier. This is required to canonicalize
3876 // a dependent nested-name-specifier involving typedefs of dependent-name
3877 // types, e.g.,
3878 // typedef typename T::type T1;
3879 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003880 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3881 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003882 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003883
Eli Friedman16412ef2012-03-03 04:09:56 +00003884 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3885 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3886 // first place?
John McCall3b657512011-01-19 10:06:00 +00003887 return NestedNameSpecifier::Create(*this, 0, false,
3888 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003889 }
3890
3891 case NestedNameSpecifier::Global:
3892 // The global specifier is canonical and unique.
3893 return NNS;
3894 }
3895
David Blaikie7530c032012-01-17 06:56:22 +00003896 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003897}
3898
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003899
Jay Foad4ba2a172011-01-12 09:06:06 +00003900const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003901 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003902 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003903 // Handle the common positive case fast.
3904 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3905 return AT;
3906 }
Mike Stump1eb44332009-09-09 15:08:12 +00003907
John McCall0953e762009-09-24 19:53:00 +00003908 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003909 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003910 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003911
John McCall0953e762009-09-24 19:53:00 +00003912 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003913 // implements C99 6.7.3p8: "If the specification of an array type includes
3914 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003915
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003916 // If we get here, we either have type qualifiers on the type, or we have
3917 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003918 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003919
John McCall3b657512011-01-19 10:06:00 +00003920 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003921 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003922
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003923 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003924 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003925 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003926 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003927
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003928 // Otherwise, we have an array and we have qualifiers on it. Push the
3929 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003930 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003931
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003932 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3933 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3934 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003935 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003936 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3937 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3938 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003939 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003940
Mike Stump1eb44332009-09-09 15:08:12 +00003941 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003942 = dyn_cast<DependentSizedArrayType>(ATy))
3943 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003944 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003945 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003946 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003947 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003948 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003950 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003951 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003952 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003953 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003954 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003955 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003956}
3957
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003958QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003959 // C99 6.7.5.3p7:
3960 // A declaration of a parameter as "array of type" shall be
3961 // adjusted to "qualified pointer to type", where the type
3962 // qualifiers (if any) are those specified within the [ and ] of
3963 // the array type derivation.
3964 if (T->isArrayType())
3965 return getArrayDecayedType(T);
3966
3967 // C99 6.7.5.3p8:
3968 // A declaration of a parameter as "function returning type"
3969 // shall be adjusted to "pointer to function returning type", as
3970 // in 6.3.2.1.
3971 if (T->isFunctionType())
3972 return getPointerType(T);
3973
3974 return T;
3975}
3976
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003977QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003978 T = getVariableArrayDecayedType(T);
3979 T = getAdjustedParameterType(T);
3980 return T.getUnqualifiedType();
3981}
3982
Chris Lattnere6327742008-04-02 05:18:44 +00003983/// getArrayDecayedType - Return the properly qualified result of decaying the
3984/// specified array type to a pointer. This operation is non-trivial when
3985/// handling typedefs etc. The canonical type of "T" must be an array type,
3986/// this returns a pointer to a properly qualified element of the array.
3987///
3988/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003989QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003990 // Get the element type with 'getAsArrayType' so that we don't lose any
3991 // typedefs in the element type of the array. This also handles propagation
3992 // of type qualifiers from the array type into the element type if present
3993 // (C99 6.7.3p8).
3994 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3995 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003997 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003998
3999 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004000 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004001}
4002
John McCall3b657512011-01-19 10:06:00 +00004003QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4004 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004005}
4006
John McCall3b657512011-01-19 10:06:00 +00004007QualType ASTContext::getBaseElementType(QualType type) const {
4008 Qualifiers qs;
4009 while (true) {
4010 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004011 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004012 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004013
John McCall3b657512011-01-19 10:06:00 +00004014 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004015 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004016 }
Mike Stump1eb44332009-09-09 15:08:12 +00004017
John McCall3b657512011-01-19 10:06:00 +00004018 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004019}
4020
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004021/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004022uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004023ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4024 uint64_t ElementCount = 1;
4025 do {
4026 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004027 CA = dyn_cast_or_null<ConstantArrayType>(
4028 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004029 } while (CA);
4030 return ElementCount;
4031}
4032
Reid Spencer5f016e22007-07-11 17:01:13 +00004033/// getFloatingRank - Return a relative rank for floating point types.
4034/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004035static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004036 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004037 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004038
John McCall183700f2009-09-21 23:43:11 +00004039 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4040 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004041 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004042 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004043 case BuiltinType::Float: return FloatRank;
4044 case BuiltinType::Double: return DoubleRank;
4045 case BuiltinType::LongDouble: return LongDoubleRank;
4046 }
4047}
4048
Mike Stump1eb44332009-09-09 15:08:12 +00004049/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4050/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004051/// 'typeDomain' is a real floating point or complex type.
4052/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004053QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4054 QualType Domain) const {
4055 FloatingRank EltRank = getFloatingRank(Size);
4056 if (Domain->isComplexType()) {
4057 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004058 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004059 case FloatRank: return FloatComplexTy;
4060 case DoubleRank: return DoubleComplexTy;
4061 case LongDoubleRank: return LongDoubleComplexTy;
4062 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004063 }
Chris Lattner1361b112008-04-06 23:58:54 +00004064
4065 assert(Domain->isRealFloatingType() && "Unknown domain!");
4066 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004067 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00004068 case FloatRank: return FloatTy;
4069 case DoubleRank: return DoubleTy;
4070 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004071 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004072 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004073}
4074
Chris Lattner7cfeb082008-04-06 23:55:33 +00004075/// getFloatingTypeOrder - Compare the rank of the two specified floating
4076/// point types, ignoring the domain of the type (i.e. 'double' ==
4077/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004078/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004079int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004080 FloatingRank LHSR = getFloatingRank(LHS);
4081 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004082
Chris Lattnera75cea32008-04-06 23:38:49 +00004083 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004084 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004085 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004086 return 1;
4087 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004088}
4089
Chris Lattnerf52ab252008-04-06 22:59:24 +00004090/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4091/// routine will assert if passed a built-in type that isn't an integer or enum,
4092/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004093unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004094 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004095
Chris Lattnerf52ab252008-04-06 22:59:24 +00004096 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004097 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004098 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004099 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004100 case BuiltinType::Char_S:
4101 case BuiltinType::Char_U:
4102 case BuiltinType::SChar:
4103 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004104 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004105 case BuiltinType::Short:
4106 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004107 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004108 case BuiltinType::Int:
4109 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004110 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004111 case BuiltinType::Long:
4112 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004113 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004114 case BuiltinType::LongLong:
4115 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004116 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004117 case BuiltinType::Int128:
4118 case BuiltinType::UInt128:
4119 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004120 }
4121}
4122
Eli Friedman04e83572009-08-20 04:21:42 +00004123/// \brief Whether this is a promotable bitfield reference according
4124/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4125///
4126/// \returns the type this bit-field will promote to, or NULL if no
4127/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004128QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004129 if (E->isTypeDependent() || E->isValueDependent())
4130 return QualType();
4131
Eli Friedman04e83572009-08-20 04:21:42 +00004132 FieldDecl *Field = E->getBitField();
4133 if (!Field)
4134 return QualType();
4135
4136 QualType FT = Field->getType();
4137
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004138 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004139 uint64_t IntSize = getTypeSize(IntTy);
4140 // GCC extension compatibility: if the bit-field size is less than or equal
4141 // to the size of int, it gets promoted no matter what its type is.
4142 // For instance, unsigned long bf : 4 gets promoted to signed int.
4143 if (BitWidth < IntSize)
4144 return IntTy;
4145
4146 if (BitWidth == IntSize)
4147 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4148
4149 // Types bigger than int are not subject to promotions, and therefore act
4150 // like the base type.
4151 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4152 // is ridiculous.
4153 return QualType();
4154}
4155
Eli Friedmana95d7572009-08-19 07:44:53 +00004156/// getPromotedIntegerType - Returns the type that Promotable will
4157/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4158/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004159QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004160 assert(!Promotable.isNull());
4161 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004162 if (const EnumType *ET = Promotable->getAs<EnumType>())
4163 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004164
4165 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4166 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4167 // (3.9.1) can be converted to a prvalue of the first of the following
4168 // types that can represent all the values of its underlying type:
4169 // int, unsigned int, long int, unsigned long int, long long int, or
4170 // unsigned long long int [...]
4171 // FIXME: Is there some better way to compute this?
4172 if (BT->getKind() == BuiltinType::WChar_S ||
4173 BT->getKind() == BuiltinType::WChar_U ||
4174 BT->getKind() == BuiltinType::Char16 ||
4175 BT->getKind() == BuiltinType::Char32) {
4176 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4177 uint64_t FromSize = getTypeSize(BT);
4178 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4179 LongLongTy, UnsignedLongLongTy };
4180 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4181 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4182 if (FromSize < ToSize ||
4183 (FromSize == ToSize &&
4184 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4185 return PromoteTypes[Idx];
4186 }
4187 llvm_unreachable("char type should fit into long long");
4188 }
4189 }
4190
4191 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004192 if (Promotable->isSignedIntegerType())
4193 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004194 uint64_t PromotableSize = getIntWidth(Promotable);
4195 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004196 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4197 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4198}
4199
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004200/// \brief Recurses in pointer/array types until it finds an objc retainable
4201/// type and returns its ownership.
4202Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4203 while (!T.isNull()) {
4204 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4205 return T.getObjCLifetime();
4206 if (T->isArrayType())
4207 T = getBaseElementType(T);
4208 else if (const PointerType *PT = T->getAs<PointerType>())
4209 T = PT->getPointeeType();
4210 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004211 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004212 else
4213 break;
4214 }
4215
4216 return Qualifiers::OCL_None;
4217}
4218
Mike Stump1eb44332009-09-09 15:08:12 +00004219/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004220/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004221/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004222int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004223 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4224 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004225 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004226
Chris Lattnerf52ab252008-04-06 22:59:24 +00004227 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4228 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004229
Chris Lattner7cfeb082008-04-06 23:55:33 +00004230 unsigned LHSRank = getIntegerRank(LHSC);
4231 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Chris Lattner7cfeb082008-04-06 23:55:33 +00004233 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4234 if (LHSRank == RHSRank) return 0;
4235 return LHSRank > RHSRank ? 1 : -1;
4236 }
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Chris Lattner7cfeb082008-04-06 23:55:33 +00004238 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4239 if (LHSUnsigned) {
4240 // If the unsigned [LHS] type is larger, return it.
4241 if (LHSRank >= RHSRank)
4242 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004243
Chris Lattner7cfeb082008-04-06 23:55:33 +00004244 // If the signed type can represent all values of the unsigned type, it
4245 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004246 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004247 return -1;
4248 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004249
Chris Lattner7cfeb082008-04-06 23:55:33 +00004250 // If the unsigned [RHS] type is larger, return it.
4251 if (RHSRank >= LHSRank)
4252 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Chris Lattner7cfeb082008-04-06 23:55:33 +00004254 // If the signed type can represent all values of the unsigned type, it
4255 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004256 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004257 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004258}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004259
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004260static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004261CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4262 DeclContext *DC, IdentifierInfo *Id) {
4263 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004264 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004265 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004266 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004267 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004268}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004269
Mike Stump1eb44332009-09-09 15:08:12 +00004270// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004271QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004272 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004273 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004274 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004275 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004276 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004277
Anders Carlssonf06273f2007-11-19 00:25:30 +00004278 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Anders Carlsson71993dd2007-08-17 05:31:46 +00004280 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004281 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004282 // int flags;
4283 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004284 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004285 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004286 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004287 FieldTypes[3] = LongTy;
4288
Anders Carlsson71993dd2007-08-17 05:31:46 +00004289 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004290 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004291 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004292 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004293 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004294 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004295 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004296 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004297 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004298 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004299 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004300 }
4301
Douglas Gregor838db382010-02-11 01:19:42 +00004302 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004303 }
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Anders Carlsson71993dd2007-08-17 05:31:46 +00004305 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004306}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004307
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004308QualType ASTContext::getObjCSuperType() const {
4309 if (ObjCSuperType.isNull()) {
4310 RecordDecl *ObjCSuperTypeDecl =
4311 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4312 TUDecl->addDecl(ObjCSuperTypeDecl);
4313 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4314 }
4315 return ObjCSuperType;
4316}
4317
Douglas Gregor319ac892009-04-23 22:29:11 +00004318void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004319 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004320 assert(Rec && "Invalid CFConstantStringType");
4321 CFConstantStringTypeDecl = Rec->getDecl();
4322}
4323
Jay Foad4ba2a172011-01-12 09:06:06 +00004324QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004325 if (BlockDescriptorType)
4326 return getTagDeclType(BlockDescriptorType);
4327
4328 RecordDecl *T;
4329 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004330 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004331 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004332 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004333
4334 QualType FieldTypes[] = {
4335 UnsignedLongTy,
4336 UnsignedLongTy,
4337 };
4338
4339 const char *FieldNames[] = {
4340 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004341 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004342 };
4343
4344 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004345 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004346 SourceLocation(),
4347 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004348 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004349 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004350 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004351 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004352 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004353 T->addDecl(Field);
4354 }
4355
Douglas Gregor838db382010-02-11 01:19:42 +00004356 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004357
4358 BlockDescriptorType = T;
4359
4360 return getTagDeclType(BlockDescriptorType);
4361}
4362
Jay Foad4ba2a172011-01-12 09:06:06 +00004363QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004364 if (BlockDescriptorExtendedType)
4365 return getTagDeclType(BlockDescriptorExtendedType);
4366
4367 RecordDecl *T;
4368 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004369 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004370 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004371 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004372
4373 QualType FieldTypes[] = {
4374 UnsignedLongTy,
4375 UnsignedLongTy,
4376 getPointerType(VoidPtrTy),
4377 getPointerType(VoidPtrTy)
4378 };
4379
4380 const char *FieldNames[] = {
4381 "reserved",
4382 "Size",
4383 "CopyFuncPtr",
4384 "DestroyFuncPtr"
4385 };
4386
4387 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004388 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004389 SourceLocation(),
4390 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004391 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004392 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004393 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004394 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004395 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004396 T->addDecl(Field);
4397 }
4398
Douglas Gregor838db382010-02-11 01:19:42 +00004399 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004400
4401 BlockDescriptorExtendedType = T;
4402
4403 return getTagDeclType(BlockDescriptorExtendedType);
4404}
4405
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004406/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4407/// requires copy/dispose. Note that this must match the logic
4408/// in buildByrefHelpers.
4409bool ASTContext::BlockRequiresCopying(QualType Ty,
4410 const VarDecl *D) {
4411 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4412 const Expr *copyExpr = getBlockVarCopyInits(D);
4413 if (!copyExpr && record->hasTrivialDestructor()) return false;
4414
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004415 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004416 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004417
4418 if (!Ty->isObjCRetainableType()) return false;
4419
4420 Qualifiers qs = Ty.getQualifiers();
4421
4422 // If we have lifetime, that dominates.
4423 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4424 assert(getLangOpts().ObjCAutoRefCount);
4425
4426 switch (lifetime) {
4427 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4428
4429 // These are just bits as far as the runtime is concerned.
4430 case Qualifiers::OCL_ExplicitNone:
4431 case Qualifiers::OCL_Autoreleasing:
4432 return false;
4433
4434 // Tell the runtime that this is ARC __weak, called by the
4435 // byref routines.
4436 case Qualifiers::OCL_Weak:
4437 // ARC __strong __block variables need to be retained.
4438 case Qualifiers::OCL_Strong:
4439 return true;
4440 }
4441 llvm_unreachable("fell out of lifetime switch!");
4442 }
4443 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4444 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004445}
4446
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004447bool ASTContext::getByrefLifetime(QualType Ty,
4448 Qualifiers::ObjCLifetime &LifeTime,
4449 bool &HasByrefExtendedLayout) const {
4450
4451 if (!getLangOpts().ObjC1 ||
4452 getLangOpts().getGC() != LangOptions::NonGC)
4453 return false;
4454
4455 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004456 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004457 HasByrefExtendedLayout = true;
4458 LifeTime = Qualifiers::OCL_None;
4459 }
4460 else if (getLangOpts().ObjCAutoRefCount)
4461 LifeTime = Ty.getObjCLifetime();
4462 // MRR.
4463 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4464 LifeTime = Qualifiers::OCL_ExplicitNone;
4465 else
4466 LifeTime = Qualifiers::OCL_None;
4467 return true;
4468}
4469
Douglas Gregore97179c2011-09-08 01:46:34 +00004470TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4471 if (!ObjCInstanceTypeDecl)
4472 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4473 getTranslationUnitDecl(),
4474 SourceLocation(),
4475 SourceLocation(),
4476 &Idents.get("instancetype"),
4477 getTrivialTypeSourceInfo(getObjCIdType()));
4478 return ObjCInstanceTypeDecl;
4479}
4480
Anders Carlssone8c49532007-10-29 06:33:42 +00004481// This returns true if a type has been typedefed to BOOL:
4482// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004483static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004484 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004485 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4486 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004487
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004488 return false;
4489}
4490
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004491/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004492/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004493CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004494 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4495 return CharUnits::Zero();
4496
Ken Dyck199c3d62010-01-11 17:06:35 +00004497 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004498
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004499 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004500 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004501 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004502 // Treat arrays as pointers, since that's how they're passed in.
4503 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004504 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004505 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004506}
4507
4508static inline
4509std::string charUnitsToString(const CharUnits &CU) {
4510 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004511}
4512
John McCall6b5a61b2011-02-07 10:33:21 +00004513/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004514/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004515std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4516 std::string S;
4517
David Chisnall5e530af2009-11-17 19:33:30 +00004518 const BlockDecl *Decl = Expr->getBlockDecl();
4519 QualType BlockTy =
4520 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4521 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004522 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004523 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4524 BlockTy->getAs<FunctionType>()->getResultType(),
4525 S, true /*Extended*/);
4526 else
4527 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4528 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004529 // Compute size of all parameters.
4530 // Start with computing size of a pointer in number of bytes.
4531 // FIXME: There might(should) be a better way of doing this computation!
4532 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004533 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4534 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004535 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004536 E = Decl->param_end(); PI != E; ++PI) {
4537 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004538 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004539 if (sz.isZero())
4540 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004541 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004542 ParmOffset += sz;
4543 }
4544 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004545 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004546 // Block pointer and offset.
4547 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004548
4549 // Argument types.
4550 ParmOffset = PtrSize;
4551 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4552 Decl->param_end(); PI != E; ++PI) {
4553 ParmVarDecl *PVDecl = *PI;
4554 QualType PType = PVDecl->getOriginalType();
4555 if (const ArrayType *AT =
4556 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4557 // Use array's original type only if it has known number of
4558 // elements.
4559 if (!isa<ConstantArrayType>(AT))
4560 PType = PVDecl->getType();
4561 } else if (PType->isFunctionType())
4562 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004563 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004564 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4565 S, true /*Extended*/);
4566 else
4567 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004568 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004569 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004570 }
John McCall6b5a61b2011-02-07 10:33:21 +00004571
4572 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004573}
4574
Douglas Gregorf968d832011-05-27 01:19:52 +00004575bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004576 std::string& S) {
4577 // Encode result type.
4578 getObjCEncodingForType(Decl->getResultType(), S);
4579 CharUnits ParmOffset;
4580 // Compute size of all parameters.
4581 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4582 E = Decl->param_end(); PI != E; ++PI) {
4583 QualType PType = (*PI)->getType();
4584 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004585 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004586 continue;
4587
David Chisnall5389f482010-12-30 14:05:53 +00004588 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004589 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004590 ParmOffset += sz;
4591 }
4592 S += charUnitsToString(ParmOffset);
4593 ParmOffset = CharUnits::Zero();
4594
4595 // Argument types.
4596 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4597 E = Decl->param_end(); PI != E; ++PI) {
4598 ParmVarDecl *PVDecl = *PI;
4599 QualType PType = PVDecl->getOriginalType();
4600 if (const ArrayType *AT =
4601 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4602 // Use array's original type only if it has known number of
4603 // elements.
4604 if (!isa<ConstantArrayType>(AT))
4605 PType = PVDecl->getType();
4606 } else if (PType->isFunctionType())
4607 PType = PVDecl->getType();
4608 getObjCEncodingForType(PType, S);
4609 S += charUnitsToString(ParmOffset);
4610 ParmOffset += getObjCEncodingTypeSize(PType);
4611 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004612
4613 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004614}
4615
Bob Wilsondc8dab62011-11-30 01:57:58 +00004616/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4617/// method parameter or return type. If Extended, include class names and
4618/// block object types.
4619void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4620 QualType T, std::string& S,
4621 bool Extended) const {
4622 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4623 getObjCEncodingForTypeQualifier(QT, S);
4624 // Encode parameter type.
4625 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4626 true /*OutermostType*/,
4627 false /*EncodingProperty*/,
4628 false /*StructField*/,
4629 Extended /*EncodeBlockParameters*/,
4630 Extended /*EncodeClassNames*/);
4631}
4632
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004633/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004634/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004635bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004636 std::string& S,
4637 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004638 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004639 // Encode return type.
4640 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4641 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004642 // Compute size of all parameters.
4643 // Start with computing size of a pointer in number of bytes.
4644 // FIXME: There might(should) be a better way of doing this computation!
4645 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004646 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004647 // The first two arguments (self and _cmd) are pointers; account for
4648 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004649 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004650 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004651 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004652 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004653 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004654 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004655 continue;
4656
Ken Dyck199c3d62010-01-11 17:06:35 +00004657 assert (sz.isPositive() &&
4658 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004659 ParmOffset += sz;
4660 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004661 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004662 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004663 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004664
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004665 // Argument types.
4666 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004667 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004668 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004669 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004670 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004671 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004672 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4673 // Use array's original type only if it has known number of
4674 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004675 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004676 PType = PVDecl->getType();
4677 } else if (PType->isFunctionType())
4678 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004679 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4680 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004681 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004682 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004683 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004684
4685 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004686}
4687
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004688/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004689/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004690/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4691/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004692/// Property attributes are stored as a comma-delimited C string. The simple
4693/// attributes readonly and bycopy are encoded as single characters. The
4694/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4695/// encoded as single characters, followed by an identifier. Property types
4696/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004697/// these attributes are defined by the following enumeration:
4698/// @code
4699/// enum PropertyAttributes {
4700/// kPropertyReadOnly = 'R', // property is read-only.
4701/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4702/// kPropertyByref = '&', // property is a reference to the value last assigned
4703/// kPropertyDynamic = 'D', // property is dynamic
4704/// kPropertyGetter = 'G', // followed by getter selector name
4705/// kPropertySetter = 'S', // followed by setter selector name
4706/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004707/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004708/// kPropertyWeak = 'W' // 'weak' property
4709/// kPropertyStrong = 'P' // property GC'able
4710/// kPropertyNonAtomic = 'N' // property non-atomic
4711/// };
4712/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004713void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004714 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004715 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004716 // Collect information from the property implementation decl(s).
4717 bool Dynamic = false;
4718 ObjCPropertyImplDecl *SynthesizePID = 0;
4719
4720 // FIXME: Duplicated code due to poor abstraction.
4721 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004722 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004723 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4724 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004725 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004726 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004727 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004728 if (PID->getPropertyDecl() == PD) {
4729 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4730 Dynamic = true;
4731 } else {
4732 SynthesizePID = PID;
4733 }
4734 }
4735 }
4736 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004737 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004738 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004739 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004740 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004741 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004742 if (PID->getPropertyDecl() == PD) {
4743 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4744 Dynamic = true;
4745 } else {
4746 SynthesizePID = PID;
4747 }
4748 }
Mike Stump1eb44332009-09-09 15:08:12 +00004749 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004750 }
4751 }
4752
4753 // FIXME: This is not very efficient.
4754 S = "T";
4755
4756 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004757 // GCC has some special rules regarding encoding of properties which
4758 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004759 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004760 true /* outermost type */,
4761 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004762
4763 if (PD->isReadOnly()) {
4764 S += ",R";
4765 } else {
4766 switch (PD->getSetterKind()) {
4767 case ObjCPropertyDecl::Assign: break;
4768 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004769 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004770 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004771 }
4772 }
4773
4774 // It really isn't clear at all what this means, since properties
4775 // are "dynamic by default".
4776 if (Dynamic)
4777 S += ",D";
4778
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004779 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4780 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004782 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4783 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004784 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004785 }
4786
4787 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4788 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004789 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004790 }
4791
4792 if (SynthesizePID) {
4793 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4794 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004795 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004796 }
4797
4798 // FIXME: OBJCGC: weak & strong
4799}
4800
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004801/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004802/// Another legacy compatibility encoding: 32-bit longs are encoded as
4803/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004804/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4805///
4806void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004807 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004808 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004809 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004810 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004811 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004812 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004813 PointeeTy = IntTy;
4814 }
4815 }
4816}
4817
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004818void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004819 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004820 // We follow the behavior of gcc, expanding structures which are
4821 // directly pointed to, and expanding embedded structures. Note that
4822 // these rules are sufficient to prevent recursive encoding of the
4823 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004824 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004825 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004826}
4827
John McCall3624e9e2012-12-20 02:45:14 +00004828static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4829 BuiltinType::Kind kind) {
4830 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004831 case BuiltinType::Void: return 'v';
4832 case BuiltinType::Bool: return 'B';
4833 case BuiltinType::Char_U:
4834 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00004835 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00004836 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00004837 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00004838 case BuiltinType::UInt: return 'I';
4839 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00004840 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004841 case BuiltinType::UInt128: return 'T';
4842 case BuiltinType::ULongLong: return 'Q';
4843 case BuiltinType::Char_S:
4844 case BuiltinType::SChar: return 'c';
4845 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004846 case BuiltinType::WChar_S:
4847 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004848 case BuiltinType::Int: return 'i';
4849 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00004850 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004851 case BuiltinType::LongLong: return 'q';
4852 case BuiltinType::Int128: return 't';
4853 case BuiltinType::Float: return 'f';
4854 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004855 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00004856 case BuiltinType::NullPtr: return '*'; // like char*
4857
4858 case BuiltinType::Half:
4859 // FIXME: potentially need @encodes for these!
4860 return ' ';
4861
4862 case BuiltinType::ObjCId:
4863 case BuiltinType::ObjCClass:
4864 case BuiltinType::ObjCSel:
4865 llvm_unreachable("@encoding ObjC primitive type");
4866
4867 // OpenCL and placeholder types don't need @encodings.
4868 case BuiltinType::OCLImage1d:
4869 case BuiltinType::OCLImage1dArray:
4870 case BuiltinType::OCLImage1dBuffer:
4871 case BuiltinType::OCLImage2d:
4872 case BuiltinType::OCLImage2dArray:
4873 case BuiltinType::OCLImage3d:
4874 case BuiltinType::Dependent:
4875#define BUILTIN_TYPE(KIND, ID)
4876#define PLACEHOLDER_TYPE(KIND, ID) \
4877 case BuiltinType::KIND:
4878#include "clang/AST/BuiltinTypes.def"
4879 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00004880 }
David Blaikie719e53f2013-01-09 17:48:41 +00004881 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00004882}
4883
Douglas Gregor5471bc82011-09-08 17:18:35 +00004884static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4885 EnumDecl *Enum = ET->getDecl();
4886
4887 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4888 if (!Enum->isFixed())
4889 return 'i';
4890
4891 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00004892 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4893 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00004894}
4895
Jay Foad4ba2a172011-01-12 09:06:06 +00004896static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004897 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004898 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004899 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004900 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4901 // The GNU runtime requires more information; bitfields are encoded as b,
4902 // then the offset (in bits) of the first element, then the type of the
4903 // bitfield, then the size in bits. For example, in this structure:
4904 //
4905 // struct
4906 // {
4907 // int integer;
4908 // int flags:2;
4909 // };
4910 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4911 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4912 // information is not especially sensible, but we're stuck with it for
4913 // compatibility with GCC, although providing it breaks anything that
4914 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004915 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004916 const RecordDecl *RD = FD->getParent();
4917 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004918 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004919 if (const EnumType *ET = T->getAs<EnumType>())
4920 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00004921 else {
4922 const BuiltinType *BT = T->castAs<BuiltinType>();
4923 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4924 }
David Chisnall64fd7e82010-06-04 01:10:52 +00004925 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004926 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004927}
4928
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004929// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004930void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4931 bool ExpandPointedToStructures,
4932 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004933 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004934 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004935 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004936 bool StructField,
4937 bool EncodeBlockParameters,
4938 bool EncodeClassNames) const {
John McCall3624e9e2012-12-20 02:45:14 +00004939 CanQualType CT = getCanonicalType(T);
4940 switch (CT->getTypeClass()) {
4941 case Type::Builtin:
4942 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004943 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004944 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00004945 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4946 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4947 else
4948 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004949 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004950
John McCall3624e9e2012-12-20 02:45:14 +00004951 case Type::Complex: {
4952 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004953 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004954 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004955 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004956 return;
4957 }
John McCall3624e9e2012-12-20 02:45:14 +00004958
4959 case Type::Atomic: {
4960 const AtomicType *AT = T->castAs<AtomicType>();
4961 S += 'A';
4962 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
4963 false, false);
4964 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004965 }
John McCall3624e9e2012-12-20 02:45:14 +00004966
4967 // encoding for pointer or reference types.
4968 case Type::Pointer:
4969 case Type::LValueReference:
4970 case Type::RValueReference: {
4971 QualType PointeeTy;
4972 if (isa<PointerType>(CT)) {
4973 const PointerType *PT = T->castAs<PointerType>();
4974 if (PT->isObjCSelType()) {
4975 S += ':';
4976 return;
4977 }
4978 PointeeTy = PT->getPointeeType();
4979 } else {
4980 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
4981 }
4982
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004983 bool isReadOnly = false;
4984 // For historical/compatibility reasons, the read-only qualifier of the
4985 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4986 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004987 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004988 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004989 if (OutermostType && T.isConstQualified()) {
4990 isReadOnly = true;
4991 S += 'r';
4992 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004993 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004994 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004995 while (P->getAs<PointerType>())
4996 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004997 if (P.isConstQualified()) {
4998 isReadOnly = true;
4999 S += 'r';
5000 }
5001 }
5002 if (isReadOnly) {
5003 // Another legacy compatibility encoding. Some ObjC qualifier and type
5004 // combinations need to be rearranged.
5005 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005006 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005007 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005008 }
Mike Stump1eb44332009-09-09 15:08:12 +00005009
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005010 if (PointeeTy->isCharType()) {
5011 // char pointer types should be encoded as '*' unless it is a
5012 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005013 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005014 S += '*';
5015 return;
5016 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005017 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005018 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5019 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5020 S += '#';
5021 return;
5022 }
5023 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5024 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5025 S += '@';
5026 return;
5027 }
5028 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005029 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005030 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005031 getLegacyIntegralTypeEncoding(PointeeTy);
5032
Mike Stump1eb44332009-09-09 15:08:12 +00005033 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005034 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005035 return;
5036 }
John McCall3624e9e2012-12-20 02:45:14 +00005037
5038 case Type::ConstantArray:
5039 case Type::IncompleteArray:
5040 case Type::VariableArray: {
5041 const ArrayType *AT = cast<ArrayType>(CT);
5042
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005043 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005044 // Incomplete arrays are encoded as a pointer to the array element.
5045 S += '^';
5046
Mike Stump1eb44332009-09-09 15:08:12 +00005047 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005048 false, ExpandStructures, FD);
5049 } else {
5050 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005051
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005052 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5053 if (getTypeSize(CAT->getElementType()) == 0)
5054 S += '0';
5055 else
5056 S += llvm::utostr(CAT->getSize().getZExtValue());
5057 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005058 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005059 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5060 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005061 S += '0';
5062 }
Mike Stump1eb44332009-09-09 15:08:12 +00005063
5064 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005065 false, ExpandStructures, FD);
5066 S += ']';
5067 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005068 return;
5069 }
Mike Stump1eb44332009-09-09 15:08:12 +00005070
John McCall3624e9e2012-12-20 02:45:14 +00005071 case Type::FunctionNoProto:
5072 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005073 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005074 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005075
John McCall3624e9e2012-12-20 02:45:14 +00005076 case Type::Record: {
5077 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005078 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005079 // Anonymous structures print as '?'
5080 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5081 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005082 if (ClassTemplateSpecializationDecl *Spec
5083 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5084 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5085 std::string TemplateArgsStr
5086 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00005087 TemplateArgs.data(),
5088 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005089 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005090
5091 S += TemplateArgsStr;
5092 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005093 } else {
5094 S += '?';
5095 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005096 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005097 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005098 if (!RDecl->isUnion()) {
5099 getObjCEncodingForStructureImpl(RDecl, S, FD);
5100 } else {
5101 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5102 FieldEnd = RDecl->field_end();
5103 Field != FieldEnd; ++Field) {
5104 if (FD) {
5105 S += '"';
5106 S += Field->getNameAsString();
5107 S += '"';
5108 }
Mike Stump1eb44332009-09-09 15:08:12 +00005109
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005110 // Special case bit-fields.
5111 if (Field->isBitField()) {
5112 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005113 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005114 } else {
5115 QualType qt = Field->getType();
5116 getLegacyIntegralTypeEncoding(qt);
5117 getObjCEncodingForTypeImpl(qt, S, false, true,
5118 FD, /*OutermostType*/false,
5119 /*EncodingProperty*/false,
5120 /*StructField*/true);
5121 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005122 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005123 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005124 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005125 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005126 return;
5127 }
Mike Stump1eb44332009-09-09 15:08:12 +00005128
John McCall3624e9e2012-12-20 02:45:14 +00005129 case Type::BlockPointer: {
5130 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005131 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005132 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005133 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005134
5135 S += '<';
5136 // Block return type
5137 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5138 ExpandPointedToStructures, ExpandStructures,
5139 FD,
5140 false /* OutermostType */,
5141 EncodingProperty,
5142 false /* StructField */,
5143 EncodeBlockParameters,
5144 EncodeClassNames);
5145 // Block self
5146 S += "@?";
5147 // Block parameters
5148 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5149 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5150 E = FPT->arg_type_end(); I && (I != E); ++I) {
5151 getObjCEncodingForTypeImpl(*I, S,
5152 ExpandPointedToStructures,
5153 ExpandStructures,
5154 FD,
5155 false /* OutermostType */,
5156 EncodingProperty,
5157 false /* StructField */,
5158 EncodeBlockParameters,
5159 EncodeClassNames);
5160 }
5161 }
5162 S += '>';
5163 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005164 return;
5165 }
Mike Stump1eb44332009-09-09 15:08:12 +00005166
John McCall3624e9e2012-12-20 02:45:14 +00005167 case Type::ObjCObject:
5168 case Type::ObjCInterface: {
5169 // Ignore protocol qualifiers when mangling at this level.
5170 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005171
John McCall3624e9e2012-12-20 02:45:14 +00005172 // The assumption seems to be that this assert will succeed
5173 // because nested levels will have filtered out 'id' and 'Class'.
5174 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005175 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005176 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005177 S += '{';
5178 const IdentifierInfo *II = OI->getIdentifier();
5179 S += II->getName();
5180 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005181 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005182 DeepCollectObjCIvars(OI, true, Ivars);
5183 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005184 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005185 if (Field->isBitField())
5186 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005187 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005188 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005189 }
5190 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005191 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005192 }
Mike Stump1eb44332009-09-09 15:08:12 +00005193
John McCall3624e9e2012-12-20 02:45:14 +00005194 case Type::ObjCObjectPointer: {
5195 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005196 if (OPT->isObjCIdType()) {
5197 S += '@';
5198 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005199 }
Mike Stump1eb44332009-09-09 15:08:12 +00005200
Steve Naroff27d20a22009-10-28 22:03:49 +00005201 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5202 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5203 // Since this is a binary compatibility issue, need to consult with runtime
5204 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005205 S += '#';
5206 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005207 }
Mike Stump1eb44332009-09-09 15:08:12 +00005208
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005209 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005210 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005211 ExpandPointedToStructures,
5212 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005213 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005214 // Note that we do extended encoding of protocol qualifer list
5215 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005216 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005217 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5218 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005219 S += '<';
5220 S += (*I)->getNameAsString();
5221 S += '>';
5222 }
5223 S += '"';
5224 }
5225 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005226 }
Mike Stump1eb44332009-09-09 15:08:12 +00005227
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005228 QualType PointeeTy = OPT->getPointeeType();
5229 if (!EncodingProperty &&
5230 isa<TypedefType>(PointeeTy.getTypePtr())) {
5231 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005232 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005233 // {...};
5234 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005235 getObjCEncodingForTypeImpl(PointeeTy, S,
5236 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005237 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00005238 return;
5239 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005240
5241 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005242 if (OPT->getInterfaceDecl() &&
5243 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005244 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005245 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005246 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5247 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005248 S += '<';
5249 S += (*I)->getNameAsString();
5250 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005251 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005252 S += '"';
5253 }
5254 return;
5255 }
Mike Stump1eb44332009-09-09 15:08:12 +00005256
John McCall532ec7b2010-05-17 23:56:34 +00005257 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005258 // FIXME: we shoul do better than that. 'M' is available.
5259 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005260 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005261
John McCall3624e9e2012-12-20 02:45:14 +00005262 case Type::Vector:
5263 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005264 // This matches gcc's encoding, even though technically it is
5265 // insufficient.
5266 // FIXME. We should do a better job than gcc.
5267 return;
John McCall3624e9e2012-12-20 02:45:14 +00005268
5269#define ABSTRACT_TYPE(KIND, BASE)
5270#define TYPE(KIND, BASE)
5271#define DEPENDENT_TYPE(KIND, BASE) \
5272 case Type::KIND:
5273#define NON_CANONICAL_TYPE(KIND, BASE) \
5274 case Type::KIND:
5275#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5276 case Type::KIND:
5277#include "clang/AST/TypeNodes.def"
5278 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005279 }
John McCall3624e9e2012-12-20 02:45:14 +00005280 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005281}
5282
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005283void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5284 std::string &S,
5285 const FieldDecl *FD,
5286 bool includeVBases) const {
5287 assert(RDecl && "Expected non-null RecordDecl");
5288 assert(!RDecl->isUnion() && "Should not be called for unions");
5289 if (!RDecl->getDefinition())
5290 return;
5291
5292 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5293 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5294 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5295
5296 if (CXXRec) {
5297 for (CXXRecordDecl::base_class_iterator
5298 BI = CXXRec->bases_begin(),
5299 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5300 if (!BI->isVirtual()) {
5301 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005302 if (base->isEmpty())
5303 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005304 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005305 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5306 std::make_pair(offs, base));
5307 }
5308 }
5309 }
5310
5311 unsigned i = 0;
5312 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5313 FieldEnd = RDecl->field_end();
5314 Field != FieldEnd; ++Field, ++i) {
5315 uint64_t offs = layout.getFieldOffset(i);
5316 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005317 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005318 }
5319
5320 if (CXXRec && includeVBases) {
5321 for (CXXRecordDecl::base_class_iterator
5322 BI = CXXRec->vbases_begin(),
5323 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5324 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005325 if (base->isEmpty())
5326 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005327 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005328 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5329 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5330 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005331 }
5332 }
5333
5334 CharUnits size;
5335 if (CXXRec) {
5336 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5337 } else {
5338 size = layout.getSize();
5339 }
5340
5341 uint64_t CurOffs = 0;
5342 std::multimap<uint64_t, NamedDecl *>::iterator
5343 CurLayObj = FieldOrBaseOffsets.begin();
5344
Douglas Gregor58db7a52012-04-27 22:30:01 +00005345 if (CXXRec && CXXRec->isDynamicClass() &&
5346 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005347 if (FD) {
5348 S += "\"_vptr$";
5349 std::string recname = CXXRec->getNameAsString();
5350 if (recname.empty()) recname = "?";
5351 S += recname;
5352 S += '"';
5353 }
5354 S += "^^?";
5355 CurOffs += getTypeSize(VoidPtrTy);
5356 }
5357
5358 if (!RDecl->hasFlexibleArrayMember()) {
5359 // Mark the end of the structure.
5360 uint64_t offs = toBits(size);
5361 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5362 std::make_pair(offs, (NamedDecl*)0));
5363 }
5364
5365 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5366 assert(CurOffs <= CurLayObj->first);
5367
5368 if (CurOffs < CurLayObj->first) {
5369 uint64_t padding = CurLayObj->first - CurOffs;
5370 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5371 // packing/alignment of members is different that normal, in which case
5372 // the encoding will be out-of-sync with the real layout.
5373 // If the runtime switches to just consider the size of types without
5374 // taking into account alignment, we could make padding explicit in the
5375 // encoding (e.g. using arrays of chars). The encoding strings would be
5376 // longer then though.
5377 CurOffs += padding;
5378 }
5379
5380 NamedDecl *dcl = CurLayObj->second;
5381 if (dcl == 0)
5382 break; // reached end of structure.
5383
5384 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5385 // We expand the bases without their virtual bases since those are going
5386 // in the initial structure. Note that this differs from gcc which
5387 // expands virtual bases each time one is encountered in the hierarchy,
5388 // making the encoding type bigger than it really is.
5389 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005390 assert(!base->isEmpty());
5391 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005392 } else {
5393 FieldDecl *field = cast<FieldDecl>(dcl);
5394 if (FD) {
5395 S += '"';
5396 S += field->getNameAsString();
5397 S += '"';
5398 }
5399
5400 if (field->isBitField()) {
5401 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005402 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005403 } else {
5404 QualType qt = field->getType();
5405 getLegacyIntegralTypeEncoding(qt);
5406 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5407 /*OutermostType*/false,
5408 /*EncodingProperty*/false,
5409 /*StructField*/true);
5410 CurOffs += getTypeSize(field->getType());
5411 }
5412 }
5413 }
5414}
5415
Mike Stump1eb44332009-09-09 15:08:12 +00005416void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005417 std::string& S) const {
5418 if (QT & Decl::OBJC_TQ_In)
5419 S += 'n';
5420 if (QT & Decl::OBJC_TQ_Inout)
5421 S += 'N';
5422 if (QT & Decl::OBJC_TQ_Out)
5423 S += 'o';
5424 if (QT & Decl::OBJC_TQ_Bycopy)
5425 S += 'O';
5426 if (QT & Decl::OBJC_TQ_Byref)
5427 S += 'R';
5428 if (QT & Decl::OBJC_TQ_Oneway)
5429 S += 'V';
5430}
5431
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005432TypedefDecl *ASTContext::getObjCIdDecl() const {
5433 if (!ObjCIdDecl) {
5434 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5435 T = getObjCObjectPointerType(T);
5436 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5437 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5438 getTranslationUnitDecl(),
5439 SourceLocation(), SourceLocation(),
5440 &Idents.get("id"), IdInfo);
5441 }
5442
5443 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005444}
5445
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005446TypedefDecl *ASTContext::getObjCSelDecl() const {
5447 if (!ObjCSelDecl) {
5448 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5449 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5450 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5451 getTranslationUnitDecl(),
5452 SourceLocation(), SourceLocation(),
5453 &Idents.get("SEL"), SelInfo);
5454 }
5455 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005456}
5457
Douglas Gregor79d67262011-08-12 05:59:41 +00005458TypedefDecl *ASTContext::getObjCClassDecl() const {
5459 if (!ObjCClassDecl) {
5460 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5461 T = getObjCObjectPointerType(T);
5462 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5463 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5464 getTranslationUnitDecl(),
5465 SourceLocation(), SourceLocation(),
5466 &Idents.get("Class"), ClassInfo);
5467 }
5468
5469 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005470}
5471
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005472ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5473 if (!ObjCProtocolClassDecl) {
5474 ObjCProtocolClassDecl
5475 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5476 SourceLocation(),
5477 &Idents.get("Protocol"),
5478 /*PrevDecl=*/0,
5479 SourceLocation(), true);
5480 }
5481
5482 return ObjCProtocolClassDecl;
5483}
5484
Meador Ingec5613b22012-06-16 03:34:49 +00005485//===----------------------------------------------------------------------===//
5486// __builtin_va_list Construction Functions
5487//===----------------------------------------------------------------------===//
5488
5489static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5490 // typedef char* __builtin_va_list;
5491 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5492 TypeSourceInfo *TInfo
5493 = Context->getTrivialTypeSourceInfo(CharPtrType);
5494
5495 TypedefDecl *VaListTypeDecl
5496 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5497 Context->getTranslationUnitDecl(),
5498 SourceLocation(), SourceLocation(),
5499 &Context->Idents.get("__builtin_va_list"),
5500 TInfo);
5501 return VaListTypeDecl;
5502}
5503
5504static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5505 // typedef void* __builtin_va_list;
5506 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5507 TypeSourceInfo *TInfo
5508 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5509
5510 TypedefDecl *VaListTypeDecl
5511 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5512 Context->getTranslationUnitDecl(),
5513 SourceLocation(), SourceLocation(),
5514 &Context->Idents.get("__builtin_va_list"),
5515 TInfo);
5516 return VaListTypeDecl;
5517}
5518
5519static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5520 // typedef struct __va_list_tag {
5521 RecordDecl *VaListTagDecl;
5522
5523 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5524 Context->getTranslationUnitDecl(),
5525 &Context->Idents.get("__va_list_tag"));
5526 VaListTagDecl->startDefinition();
5527
5528 const size_t NumFields = 5;
5529 QualType FieldTypes[NumFields];
5530 const char *FieldNames[NumFields];
5531
5532 // unsigned char gpr;
5533 FieldTypes[0] = Context->UnsignedCharTy;
5534 FieldNames[0] = "gpr";
5535
5536 // unsigned char fpr;
5537 FieldTypes[1] = Context->UnsignedCharTy;
5538 FieldNames[1] = "fpr";
5539
5540 // unsigned short reserved;
5541 FieldTypes[2] = Context->UnsignedShortTy;
5542 FieldNames[2] = "reserved";
5543
5544 // void* overflow_arg_area;
5545 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5546 FieldNames[3] = "overflow_arg_area";
5547
5548 // void* reg_save_area;
5549 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5550 FieldNames[4] = "reg_save_area";
5551
5552 // Create fields
5553 for (unsigned i = 0; i < NumFields; ++i) {
5554 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5555 SourceLocation(),
5556 SourceLocation(),
5557 &Context->Idents.get(FieldNames[i]),
5558 FieldTypes[i], /*TInfo=*/0,
5559 /*BitWidth=*/0,
5560 /*Mutable=*/false,
5561 ICIS_NoInit);
5562 Field->setAccess(AS_public);
5563 VaListTagDecl->addDecl(Field);
5564 }
5565 VaListTagDecl->completeDefinition();
5566 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005567 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005568
5569 // } __va_list_tag;
5570 TypedefDecl *VaListTagTypedefDecl
5571 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5572 Context->getTranslationUnitDecl(),
5573 SourceLocation(), SourceLocation(),
5574 &Context->Idents.get("__va_list_tag"),
5575 Context->getTrivialTypeSourceInfo(VaListTagType));
5576 QualType VaListTagTypedefType =
5577 Context->getTypedefType(VaListTagTypedefDecl);
5578
5579 // typedef __va_list_tag __builtin_va_list[1];
5580 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5581 QualType VaListTagArrayType
5582 = Context->getConstantArrayType(VaListTagTypedefType,
5583 Size, ArrayType::Normal, 0);
5584 TypeSourceInfo *TInfo
5585 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5586 TypedefDecl *VaListTypedefDecl
5587 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5588 Context->getTranslationUnitDecl(),
5589 SourceLocation(), SourceLocation(),
5590 &Context->Idents.get("__builtin_va_list"),
5591 TInfo);
5592
5593 return VaListTypedefDecl;
5594}
5595
5596static TypedefDecl *
5597CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5598 // typedef struct __va_list_tag {
5599 RecordDecl *VaListTagDecl;
5600 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5601 Context->getTranslationUnitDecl(),
5602 &Context->Idents.get("__va_list_tag"));
5603 VaListTagDecl->startDefinition();
5604
5605 const size_t NumFields = 4;
5606 QualType FieldTypes[NumFields];
5607 const char *FieldNames[NumFields];
5608
5609 // unsigned gp_offset;
5610 FieldTypes[0] = Context->UnsignedIntTy;
5611 FieldNames[0] = "gp_offset";
5612
5613 // unsigned fp_offset;
5614 FieldTypes[1] = Context->UnsignedIntTy;
5615 FieldNames[1] = "fp_offset";
5616
5617 // void* overflow_arg_area;
5618 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5619 FieldNames[2] = "overflow_arg_area";
5620
5621 // void* reg_save_area;
5622 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5623 FieldNames[3] = "reg_save_area";
5624
5625 // Create fields
5626 for (unsigned i = 0; i < NumFields; ++i) {
5627 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5628 VaListTagDecl,
5629 SourceLocation(),
5630 SourceLocation(),
5631 &Context->Idents.get(FieldNames[i]),
5632 FieldTypes[i], /*TInfo=*/0,
5633 /*BitWidth=*/0,
5634 /*Mutable=*/false,
5635 ICIS_NoInit);
5636 Field->setAccess(AS_public);
5637 VaListTagDecl->addDecl(Field);
5638 }
5639 VaListTagDecl->completeDefinition();
5640 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005641 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005642
5643 // } __va_list_tag;
5644 TypedefDecl *VaListTagTypedefDecl
5645 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5646 Context->getTranslationUnitDecl(),
5647 SourceLocation(), SourceLocation(),
5648 &Context->Idents.get("__va_list_tag"),
5649 Context->getTrivialTypeSourceInfo(VaListTagType));
5650 QualType VaListTagTypedefType =
5651 Context->getTypedefType(VaListTagTypedefDecl);
5652
5653 // typedef __va_list_tag __builtin_va_list[1];
5654 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5655 QualType VaListTagArrayType
5656 = Context->getConstantArrayType(VaListTagTypedefType,
5657 Size, ArrayType::Normal,0);
5658 TypeSourceInfo *TInfo
5659 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5660 TypedefDecl *VaListTypedefDecl
5661 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5662 Context->getTranslationUnitDecl(),
5663 SourceLocation(), SourceLocation(),
5664 &Context->Idents.get("__builtin_va_list"),
5665 TInfo);
5666
5667 return VaListTypedefDecl;
5668}
5669
5670static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5671 // typedef int __builtin_va_list[4];
5672 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5673 QualType IntArrayType
5674 = Context->getConstantArrayType(Context->IntTy,
5675 Size, ArrayType::Normal, 0);
5676 TypedefDecl *VaListTypedefDecl
5677 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5678 Context->getTranslationUnitDecl(),
5679 SourceLocation(), SourceLocation(),
5680 &Context->Idents.get("__builtin_va_list"),
5681 Context->getTrivialTypeSourceInfo(IntArrayType));
5682
5683 return VaListTypedefDecl;
5684}
5685
Logan Chieneae5a8202012-10-10 06:56:20 +00005686static TypedefDecl *
5687CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5688 RecordDecl *VaListDecl;
5689 if (Context->getLangOpts().CPlusPlus) {
5690 // namespace std { struct __va_list {
5691 NamespaceDecl *NS;
5692 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5693 Context->getTranslationUnitDecl(),
5694 /*Inline*/false, SourceLocation(),
5695 SourceLocation(), &Context->Idents.get("std"),
5696 /*PrevDecl*/0);
5697
5698 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5699 Context->getTranslationUnitDecl(),
5700 SourceLocation(), SourceLocation(),
5701 &Context->Idents.get("__va_list"));
5702
5703 VaListDecl->setDeclContext(NS);
5704
5705 } else {
5706 // struct __va_list {
5707 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5708 Context->getTranslationUnitDecl(),
5709 &Context->Idents.get("__va_list"));
5710 }
5711
5712 VaListDecl->startDefinition();
5713
5714 // void * __ap;
5715 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5716 VaListDecl,
5717 SourceLocation(),
5718 SourceLocation(),
5719 &Context->Idents.get("__ap"),
5720 Context->getPointerType(Context->VoidTy),
5721 /*TInfo=*/0,
5722 /*BitWidth=*/0,
5723 /*Mutable=*/false,
5724 ICIS_NoInit);
5725 Field->setAccess(AS_public);
5726 VaListDecl->addDecl(Field);
5727
5728 // };
5729 VaListDecl->completeDefinition();
5730
5731 // typedef struct __va_list __builtin_va_list;
5732 TypeSourceInfo *TInfo
5733 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5734
5735 TypedefDecl *VaListTypeDecl
5736 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5737 Context->getTranslationUnitDecl(),
5738 SourceLocation(), SourceLocation(),
5739 &Context->Idents.get("__builtin_va_list"),
5740 TInfo);
5741
5742 return VaListTypeDecl;
5743}
5744
Meador Ingec5613b22012-06-16 03:34:49 +00005745static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5746 TargetInfo::BuiltinVaListKind Kind) {
5747 switch (Kind) {
5748 case TargetInfo::CharPtrBuiltinVaList:
5749 return CreateCharPtrBuiltinVaListDecl(Context);
5750 case TargetInfo::VoidPtrBuiltinVaList:
5751 return CreateVoidPtrBuiltinVaListDecl(Context);
5752 case TargetInfo::PowerABIBuiltinVaList:
5753 return CreatePowerABIBuiltinVaListDecl(Context);
5754 case TargetInfo::X86_64ABIBuiltinVaList:
5755 return CreateX86_64ABIBuiltinVaListDecl(Context);
5756 case TargetInfo::PNaClABIBuiltinVaList:
5757 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00005758 case TargetInfo::AAPCSABIBuiltinVaList:
5759 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005760 }
5761
5762 llvm_unreachable("Unhandled __builtin_va_list type kind");
5763}
5764
5765TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5766 if (!BuiltinVaListDecl)
5767 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5768
5769 return BuiltinVaListDecl;
5770}
5771
Meador Ingefb40e3f2012-07-01 15:57:25 +00005772QualType ASTContext::getVaListTagType() const {
5773 // Force the creation of VaListTagTy by building the __builtin_va_list
5774 // declaration.
5775 if (VaListTagTy.isNull())
5776 (void) getBuiltinVaListDecl();
5777
5778 return VaListTagTy;
5779}
5780
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005781void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005782 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005783 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005784
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005785 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005786}
5787
John McCall0bd6feb2009-12-02 08:04:21 +00005788/// \brief Retrieve the template name that corresponds to a non-empty
5789/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005790TemplateName
5791ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5792 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005793 unsigned size = End - Begin;
5794 assert(size > 1 && "set is not overloaded!");
5795
5796 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5797 size * sizeof(FunctionTemplateDecl*));
5798 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5799
5800 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005801 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005802 NamedDecl *D = *I;
5803 assert(isa<FunctionTemplateDecl>(D) ||
5804 (isa<UsingShadowDecl>(D) &&
5805 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5806 *Storage++ = D;
5807 }
5808
5809 return TemplateName(OT);
5810}
5811
Douglas Gregor7532dc62009-03-30 22:58:21 +00005812/// \brief Retrieve the template name that represents a qualified
5813/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005814TemplateName
5815ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5816 bool TemplateKeyword,
5817 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005818 assert(NNS && "Missing nested-name-specifier in qualified template name");
5819
Douglas Gregor789b1f62010-02-04 18:10:26 +00005820 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005821 llvm::FoldingSetNodeID ID;
5822 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5823
5824 void *InsertPos = 0;
5825 QualifiedTemplateName *QTN =
5826 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5827 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005828 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5829 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005830 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5831 }
5832
5833 return TemplateName(QTN);
5834}
5835
5836/// \brief Retrieve the template name that represents a dependent
5837/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005838TemplateName
5839ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5840 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005841 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005842 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005843
5844 llvm::FoldingSetNodeID ID;
5845 DependentTemplateName::Profile(ID, NNS, Name);
5846
5847 void *InsertPos = 0;
5848 DependentTemplateName *QTN =
5849 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5850
5851 if (QTN)
5852 return TemplateName(QTN);
5853
5854 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5855 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005856 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5857 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005858 } else {
5859 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00005860 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5861 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005862 DependentTemplateName *CheckQTN =
5863 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5864 assert(!CheckQTN && "Dependent type name canonicalization broken");
5865 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005866 }
5867
5868 DependentTemplateNames.InsertNode(QTN, InsertPos);
5869 return TemplateName(QTN);
5870}
5871
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005872/// \brief Retrieve the template name that represents a dependent
5873/// template name such as \c MetaFun::template operator+.
5874TemplateName
5875ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005876 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005877 assert((!NNS || NNS->isDependent()) &&
5878 "Nested name specifier must be dependent");
5879
5880 llvm::FoldingSetNodeID ID;
5881 DependentTemplateName::Profile(ID, NNS, Operator);
5882
5883 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005884 DependentTemplateName *QTN
5885 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005886
5887 if (QTN)
5888 return TemplateName(QTN);
5889
5890 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5891 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005892 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5893 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005894 } else {
5895 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00005896 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5897 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005898
5899 DependentTemplateName *CheckQTN
5900 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5901 assert(!CheckQTN && "Dependent template name canonicalization broken");
5902 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005903 }
5904
5905 DependentTemplateNames.InsertNode(QTN, InsertPos);
5906 return TemplateName(QTN);
5907}
5908
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005909TemplateName
John McCall14606042011-06-30 08:33:18 +00005910ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5911 TemplateName replacement) const {
5912 llvm::FoldingSetNodeID ID;
5913 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5914
5915 void *insertPos = 0;
5916 SubstTemplateTemplateParmStorage *subst
5917 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5918
5919 if (!subst) {
5920 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5921 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5922 }
5923
5924 return TemplateName(subst);
5925}
5926
5927TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005928ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5929 const TemplateArgument &ArgPack) const {
5930 ASTContext &Self = const_cast<ASTContext &>(*this);
5931 llvm::FoldingSetNodeID ID;
5932 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5933
5934 void *InsertPos = 0;
5935 SubstTemplateTemplateParmPackStorage *Subst
5936 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5937
5938 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005939 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005940 ArgPack.pack_size(),
5941 ArgPack.pack_begin());
5942 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5943 }
5944
5945 return TemplateName(Subst);
5946}
5947
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005948/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005949/// TargetInfo, produce the corresponding type. The unsigned @p Type
5950/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005951CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005952 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005953 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005954 case TargetInfo::SignedShort: return ShortTy;
5955 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5956 case TargetInfo::SignedInt: return IntTy;
5957 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5958 case TargetInfo::SignedLong: return LongTy;
5959 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5960 case TargetInfo::SignedLongLong: return LongLongTy;
5961 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5962 }
5963
David Blaikieb219cfc2011-09-23 05:06:16 +00005964 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005965}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005966
5967//===----------------------------------------------------------------------===//
5968// Type Predicates.
5969//===----------------------------------------------------------------------===//
5970
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005971/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5972/// garbage collection attribute.
5973///
John McCallae278a32011-01-12 00:34:59 +00005974Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005975 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005976 return Qualifiers::GCNone;
5977
David Blaikie4e4d0842012-03-11 07:00:24 +00005978 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005979 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5980
5981 // Default behaviour under objective-C's gc is for ObjC pointers
5982 // (or pointers to them) be treated as though they were declared
5983 // as __strong.
5984 if (GCAttrs == Qualifiers::GCNone) {
5985 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5986 return Qualifiers::Strong;
5987 else if (Ty->isPointerType())
5988 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5989 } else {
5990 // It's not valid to set GC attributes on anything that isn't a
5991 // pointer.
5992#ifndef NDEBUG
5993 QualType CT = Ty->getCanonicalTypeInternal();
5994 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5995 CT = AT->getElementType();
5996 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5997#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005998 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005999 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006000}
6001
Chris Lattner6ac46a42008-04-07 06:51:04 +00006002//===----------------------------------------------------------------------===//
6003// Type Compatibility Testing
6004//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006005
Mike Stump1eb44332009-09-09 15:08:12 +00006006/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006007/// compatible.
6008static bool areCompatVectorTypes(const VectorType *LHS,
6009 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006010 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006011 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006012 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006013}
6014
Douglas Gregor255210e2010-08-06 10:14:59 +00006015bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6016 QualType SecondVec) {
6017 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6018 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6019
6020 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6021 return true;
6022
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006023 // Treat Neon vector types and most AltiVec vector types as if they are the
6024 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006025 const VectorType *First = FirstVec->getAs<VectorType>();
6026 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006027 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006028 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006029 First->getVectorKind() != VectorType::AltiVecPixel &&
6030 First->getVectorKind() != VectorType::AltiVecBool &&
6031 Second->getVectorKind() != VectorType::AltiVecPixel &&
6032 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006033 return true;
6034
6035 return false;
6036}
6037
Steve Naroff4084c302009-07-23 01:01:38 +00006038//===----------------------------------------------------------------------===//
6039// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6040//===----------------------------------------------------------------------===//
6041
6042/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6043/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006044bool
6045ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6046 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006047 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006048 return true;
6049 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6050 E = rProto->protocol_end(); PI != E; ++PI)
6051 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6052 return true;
6053 return false;
6054}
6055
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006056/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006057/// return true if lhs's protocols conform to rhs's protocol; false
6058/// otherwise.
6059bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6060 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6061 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6062 return false;
6063}
6064
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006065/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6066/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006067bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6068 QualType rhs) {
6069 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6070 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6071 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6072
6073 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6074 E = lhsQID->qual_end(); I != E; ++I) {
6075 bool match = false;
6076 ObjCProtocolDecl *lhsProto = *I;
6077 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6078 E = rhsOPT->qual_end(); J != E; ++J) {
6079 ObjCProtocolDecl *rhsProto = *J;
6080 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6081 match = true;
6082 break;
6083 }
6084 }
6085 if (!match)
6086 return false;
6087 }
6088 return true;
6089}
6090
Steve Naroff4084c302009-07-23 01:01:38 +00006091/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6092/// ObjCQualifiedIDType.
6093bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6094 bool compare) {
6095 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006096 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006097 lhs->isObjCIdType() || lhs->isObjCClassType())
6098 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006099 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006100 rhs->isObjCIdType() || rhs->isObjCClassType())
6101 return true;
6102
6103 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006104 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006105
Steve Naroff4084c302009-07-23 01:01:38 +00006106 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006107
Steve Naroff4084c302009-07-23 01:01:38 +00006108 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006109 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006110 // make sure we check the class hierarchy.
6111 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6112 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6113 E = lhsQID->qual_end(); I != E; ++I) {
6114 // when comparing an id<P> on lhs with a static type on rhs,
6115 // see if static class implements all of id's protocols, directly or
6116 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006117 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006118 return false;
6119 }
6120 }
6121 // If there are no qualifiers and no interface, we have an 'id'.
6122 return true;
6123 }
Mike Stump1eb44332009-09-09 15:08:12 +00006124 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006125 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6126 E = lhsQID->qual_end(); I != E; ++I) {
6127 ObjCProtocolDecl *lhsProto = *I;
6128 bool match = false;
6129
6130 // when comparing an id<P> on lhs with a static type on rhs,
6131 // see if static class implements all of id's protocols, directly or
6132 // through its super class and categories.
6133 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6134 E = rhsOPT->qual_end(); J != E; ++J) {
6135 ObjCProtocolDecl *rhsProto = *J;
6136 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6137 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6138 match = true;
6139 break;
6140 }
6141 }
Mike Stump1eb44332009-09-09 15:08:12 +00006142 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006143 // make sure we check the class hierarchy.
6144 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6145 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6146 E = lhsQID->qual_end(); I != E; ++I) {
6147 // when comparing an id<P> on lhs with a static type on rhs,
6148 // see if static class implements all of id's protocols, directly or
6149 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006150 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006151 match = true;
6152 break;
6153 }
6154 }
6155 }
6156 if (!match)
6157 return false;
6158 }
Mike Stump1eb44332009-09-09 15:08:12 +00006159
Steve Naroff4084c302009-07-23 01:01:38 +00006160 return true;
6161 }
Mike Stump1eb44332009-09-09 15:08:12 +00006162
Steve Naroff4084c302009-07-23 01:01:38 +00006163 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6164 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6165
Mike Stump1eb44332009-09-09 15:08:12 +00006166 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006167 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006168 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006169 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6170 E = lhsOPT->qual_end(); I != E; ++I) {
6171 ObjCProtocolDecl *lhsProto = *I;
6172 bool match = false;
6173
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006174 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006175 // see if static class implements all of id's protocols, directly or
6176 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006177 // First, lhs protocols in the qualifier list must be found, direct
6178 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006179 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6180 E = rhsQID->qual_end(); J != E; ++J) {
6181 ObjCProtocolDecl *rhsProto = *J;
6182 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6183 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6184 match = true;
6185 break;
6186 }
6187 }
6188 if (!match)
6189 return false;
6190 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006191
6192 // Static class's protocols, or its super class or category protocols
6193 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6194 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6195 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6196 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6197 // This is rather dubious but matches gcc's behavior. If lhs has
6198 // no type qualifier and its class has no static protocol(s)
6199 // assume that it is mismatch.
6200 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6201 return false;
6202 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6203 LHSInheritedProtocols.begin(),
6204 E = LHSInheritedProtocols.end(); I != E; ++I) {
6205 bool match = false;
6206 ObjCProtocolDecl *lhsProto = (*I);
6207 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6208 E = rhsQID->qual_end(); J != E; ++J) {
6209 ObjCProtocolDecl *rhsProto = *J;
6210 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6211 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6212 match = true;
6213 break;
6214 }
6215 }
6216 if (!match)
6217 return false;
6218 }
6219 }
Steve Naroff4084c302009-07-23 01:01:38 +00006220 return true;
6221 }
6222 return false;
6223}
6224
Eli Friedman3d815e72008-08-22 00:56:42 +00006225/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006226/// compatible for assignment from RHS to LHS. This handles validation of any
6227/// protocol qualifiers on the LHS or RHS.
6228///
Steve Naroff14108da2009-07-10 23:34:53 +00006229bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6230 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006231 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6232 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6233
Steve Naroffde2e22d2009-07-15 18:40:39 +00006234 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006235 if (LHS->isObjCUnqualifiedIdOrClass() ||
6236 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006237 return true;
6238
John McCallc12c5bb2010-05-15 11:32:37 +00006239 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006240 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6241 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006242 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006243
6244 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6245 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6246 QualType(RHSOPT,0));
6247
John McCallc12c5bb2010-05-15 11:32:37 +00006248 // If we have 2 user-defined types, fall into that path.
6249 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006250 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006251
Steve Naroff4084c302009-07-23 01:01:38 +00006252 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006253}
6254
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006255/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006256/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006257/// arguments in block literals. When passed as arguments, passing 'A*' where
6258/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6259/// not OK. For the return type, the opposite is not OK.
6260bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6261 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006262 const ObjCObjectPointerType *RHSOPT,
6263 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006264 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006265 return true;
6266
6267 if (LHSOPT->isObjCBuiltinType()) {
6268 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6269 }
6270
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006271 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006272 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6273 QualType(RHSOPT,0),
6274 false);
6275
6276 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6277 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6278 if (LHS && RHS) { // We have 2 user-defined types.
6279 if (LHS != RHS) {
6280 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006281 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006282 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006283 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006284 }
6285 else
6286 return true;
6287 }
6288 return false;
6289}
6290
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006291/// getIntersectionOfProtocols - This routine finds the intersection of set
6292/// of protocols inherited from two distinct objective-c pointer objects.
6293/// It is used to build composite qualifier list of the composite type of
6294/// the conditional expression involving two objective-c pointer objects.
6295static
6296void getIntersectionOfProtocols(ASTContext &Context,
6297 const ObjCObjectPointerType *LHSOPT,
6298 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006299 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006300
John McCallc12c5bb2010-05-15 11:32:37 +00006301 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6302 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6303 assert(LHS->getInterface() && "LHS must have an interface base");
6304 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006305
6306 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6307 unsigned LHSNumProtocols = LHS->getNumProtocols();
6308 if (LHSNumProtocols > 0)
6309 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6310 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006311 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006312 Context.CollectInheritedProtocols(LHS->getInterface(),
6313 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006314 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6315 LHSInheritedProtocols.end());
6316 }
6317
6318 unsigned RHSNumProtocols = RHS->getNumProtocols();
6319 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006320 ObjCProtocolDecl **RHSProtocols =
6321 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006322 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6323 if (InheritedProtocolSet.count(RHSProtocols[i]))
6324 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006325 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006326 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006327 Context.CollectInheritedProtocols(RHS->getInterface(),
6328 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006329 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6330 RHSInheritedProtocols.begin(),
6331 E = RHSInheritedProtocols.end(); I != E; ++I)
6332 if (InheritedProtocolSet.count((*I)))
6333 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006334 }
6335}
6336
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006337/// areCommonBaseCompatible - Returns common base class of the two classes if
6338/// one found. Note that this is O'2 algorithm. But it will be called as the
6339/// last type comparison in a ?-exp of ObjC pointer types before a
6340/// warning is issued. So, its invokation is extremely rare.
6341QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006342 const ObjCObjectPointerType *Lptr,
6343 const ObjCObjectPointerType *Rptr) {
6344 const ObjCObjectType *LHS = Lptr->getObjectType();
6345 const ObjCObjectType *RHS = Rptr->getObjectType();
6346 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6347 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006348 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006349 return QualType();
6350
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006351 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006352 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006353 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006354 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006355 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6356
6357 QualType Result = QualType(LHS, 0);
6358 if (!Protocols.empty())
6359 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6360 Result = getObjCObjectPointerType(Result);
6361 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006362 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006363 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006364
6365 return QualType();
6366}
6367
John McCallc12c5bb2010-05-15 11:32:37 +00006368bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6369 const ObjCObjectType *RHS) {
6370 assert(LHS->getInterface() && "LHS is not an interface type");
6371 assert(RHS->getInterface() && "RHS is not an interface type");
6372
Chris Lattner6ac46a42008-04-07 06:51:04 +00006373 // Verify that the base decls are compatible: the RHS must be a subclass of
6374 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006375 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006376 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006377
Chris Lattner6ac46a42008-04-07 06:51:04 +00006378 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6379 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006380 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006381 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006382
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006383 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6384 // more detailed analysis is required.
6385 if (RHS->getNumProtocols() == 0) {
6386 // OK, if LHS is a superclass of RHS *and*
6387 // this superclass is assignment compatible with LHS.
6388 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006389 bool IsSuperClass =
6390 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6391 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006392 // OK if conversion of LHS to SuperClass results in narrowing of types
6393 // ; i.e., SuperClass may implement at least one of the protocols
6394 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6395 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6396 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006397 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006398 // If super class has no protocols, it is not a match.
6399 if (SuperClassInheritedProtocols.empty())
6400 return false;
6401
6402 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6403 LHSPE = LHS->qual_end();
6404 LHSPI != LHSPE; LHSPI++) {
6405 bool SuperImplementsProtocol = false;
6406 ObjCProtocolDecl *LHSProto = (*LHSPI);
6407
6408 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6409 SuperClassInheritedProtocols.begin(),
6410 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6411 ObjCProtocolDecl *SuperClassProto = (*I);
6412 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6413 SuperImplementsProtocol = true;
6414 break;
6415 }
6416 }
6417 if (!SuperImplementsProtocol)
6418 return false;
6419 }
6420 return true;
6421 }
6422 return false;
6423 }
Mike Stump1eb44332009-09-09 15:08:12 +00006424
John McCallc12c5bb2010-05-15 11:32:37 +00006425 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6426 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006427 LHSPI != LHSPE; LHSPI++) {
6428 bool RHSImplementsProtocol = false;
6429
6430 // If the RHS doesn't implement the protocol on the left, the types
6431 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006432 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6433 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006434 RHSPI != RHSPE; RHSPI++) {
6435 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006436 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006437 break;
6438 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006439 }
6440 // FIXME: For better diagnostics, consider passing back the protocol name.
6441 if (!RHSImplementsProtocol)
6442 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006443 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006444 // The RHS implements all protocols listed on the LHS.
6445 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006446}
6447
Steve Naroff389bf462009-02-12 17:52:19 +00006448bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6449 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006450 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6451 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006452
Steve Naroff14108da2009-07-10 23:34:53 +00006453 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006454 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006455
6456 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6457 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006458}
6459
Douglas Gregor569c3162010-08-07 11:51:51 +00006460bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6461 return canAssignObjCInterfaces(
6462 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6463 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6464}
6465
Mike Stump1eb44332009-09-09 15:08:12 +00006466/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006467/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006468/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006469/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006470bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6471 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006472 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006473 return hasSameType(LHS, RHS);
6474
Douglas Gregor447234d2010-07-29 15:18:02 +00006475 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006476}
6477
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006478bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006479 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006480}
6481
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006482bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6483 return !mergeTypes(LHS, RHS, true).isNull();
6484}
6485
Peter Collingbourne48466752010-10-24 18:30:18 +00006486/// mergeTransparentUnionType - if T is a transparent union type and a member
6487/// of T is compatible with SubType, return the merged type, else return
6488/// QualType()
6489QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6490 bool OfBlockPointer,
6491 bool Unqualified) {
6492 if (const RecordType *UT = T->getAsUnionType()) {
6493 RecordDecl *UD = UT->getDecl();
6494 if (UD->hasAttr<TransparentUnionAttr>()) {
6495 for (RecordDecl::field_iterator it = UD->field_begin(),
6496 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006497 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006498 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6499 if (!MT.isNull())
6500 return MT;
6501 }
6502 }
6503 }
6504
6505 return QualType();
6506}
6507
6508/// mergeFunctionArgumentTypes - merge two types which appear as function
6509/// argument types
6510QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6511 bool OfBlockPointer,
6512 bool Unqualified) {
6513 // GNU extension: two types are compatible if they appear as a function
6514 // argument, one of the types is a transparent union type and the other
6515 // type is compatible with a union member
6516 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6517 Unqualified);
6518 if (!lmerge.isNull())
6519 return lmerge;
6520
6521 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6522 Unqualified);
6523 if (!rmerge.isNull())
6524 return rmerge;
6525
6526 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6527}
6528
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006529QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006530 bool OfBlockPointer,
6531 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006532 const FunctionType *lbase = lhs->getAs<FunctionType>();
6533 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006534 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6535 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006536 bool allLTypes = true;
6537 bool allRTypes = true;
6538
6539 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006540 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006541 if (OfBlockPointer) {
6542 QualType RHS = rbase->getResultType();
6543 QualType LHS = lbase->getResultType();
6544 bool UnqualifiedResult = Unqualified;
6545 if (!UnqualifiedResult)
6546 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006547 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006548 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006549 else
John McCall8cc246c2010-12-15 01:06:38 +00006550 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6551 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006552 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006553
6554 if (Unqualified)
6555 retType = retType.getUnqualifiedType();
6556
6557 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6558 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6559 if (Unqualified) {
6560 LRetType = LRetType.getUnqualifiedType();
6561 RRetType = RRetType.getUnqualifiedType();
6562 }
6563
6564 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006565 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006566 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006567 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006568
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006569 // FIXME: double check this
6570 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6571 // rbase->getRegParmAttr() != 0 &&
6572 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006573 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6574 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006575
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006576 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006577 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006578 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006579
John McCall8cc246c2010-12-15 01:06:38 +00006580 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006581 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6582 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006583 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6584 return QualType();
6585
John McCallf85e1932011-06-15 23:02:42 +00006586 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6587 return QualType();
6588
John McCall8cc246c2010-12-15 01:06:38 +00006589 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6590 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006591
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006592 if (lbaseInfo.getNoReturn() != NoReturn)
6593 allLTypes = false;
6594 if (rbaseInfo.getNoReturn() != NoReturn)
6595 allRTypes = false;
6596
John McCallf85e1932011-06-15 23:02:42 +00006597 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006598
Eli Friedman3d815e72008-08-22 00:56:42 +00006599 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006600 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6601 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006602 unsigned lproto_nargs = lproto->getNumArgs();
6603 unsigned rproto_nargs = rproto->getNumArgs();
6604
6605 // Compatible functions must have the same number of arguments
6606 if (lproto_nargs != rproto_nargs)
6607 return QualType();
6608
6609 // Variadic and non-variadic functions aren't compatible
6610 if (lproto->isVariadic() != rproto->isVariadic())
6611 return QualType();
6612
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006613 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6614 return QualType();
6615
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006616 if (LangOpts.ObjCAutoRefCount &&
6617 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6618 return QualType();
6619
Eli Friedman3d815e72008-08-22 00:56:42 +00006620 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006621 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006622 for (unsigned i = 0; i < lproto_nargs; i++) {
6623 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6624 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006625 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6626 OfBlockPointer,
6627 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006628 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006629
6630 if (Unqualified)
6631 argtype = argtype.getUnqualifiedType();
6632
Eli Friedman3d815e72008-08-22 00:56:42 +00006633 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006634 if (Unqualified) {
6635 largtype = largtype.getUnqualifiedType();
6636 rargtype = rargtype.getUnqualifiedType();
6637 }
6638
Chris Lattner61710852008-10-05 17:34:18 +00006639 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6640 allLTypes = false;
6641 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6642 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006643 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006644
Eli Friedman3d815e72008-08-22 00:56:42 +00006645 if (allLTypes) return lhs;
6646 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006647
6648 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6649 EPI.ExtInfo = einfo;
6650 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006651 }
6652
6653 if (lproto) allRTypes = false;
6654 if (rproto) allLTypes = false;
6655
Douglas Gregor72564e72009-02-26 23:50:07 +00006656 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006657 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006658 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006659 if (proto->isVariadic()) return QualType();
6660 // Check that the types are compatible with the types that
6661 // would result from default argument promotions (C99 6.7.5.3p15).
6662 // The only types actually affected are promotable integer
6663 // types and floats, which would be passed as a different
6664 // type depending on whether the prototype is visible.
6665 unsigned proto_nargs = proto->getNumArgs();
6666 for (unsigned i = 0; i < proto_nargs; ++i) {
6667 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006668
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006669 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006670 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006671 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6672 argTy = Enum->getDecl()->getIntegerType();
6673 if (argTy.isNull())
6674 return QualType();
6675 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006676
Eli Friedman3d815e72008-08-22 00:56:42 +00006677 if (argTy->isPromotableIntegerType() ||
6678 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6679 return QualType();
6680 }
6681
6682 if (allLTypes) return lhs;
6683 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006684
6685 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6686 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006687 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006688 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006689 }
6690
6691 if (allLTypes) return lhs;
6692 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006693 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006694}
6695
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006696QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006697 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006698 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006699 // C++ [expr]: If an expression initially has the type "reference to T", the
6700 // type is adjusted to "T" prior to any further analysis, the expression
6701 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006702 // expression is an lvalue unless the reference is an rvalue reference and
6703 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006704 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6705 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006706
6707 if (Unqualified) {
6708 LHS = LHS.getUnqualifiedType();
6709 RHS = RHS.getUnqualifiedType();
6710 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006711
Eli Friedman3d815e72008-08-22 00:56:42 +00006712 QualType LHSCan = getCanonicalType(LHS),
6713 RHSCan = getCanonicalType(RHS);
6714
6715 // If two types are identical, they are compatible.
6716 if (LHSCan == RHSCan)
6717 return LHS;
6718
John McCall0953e762009-09-24 19:53:00 +00006719 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006720 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6721 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006722 if (LQuals != RQuals) {
6723 // If any of these qualifiers are different, we have a type
6724 // mismatch.
6725 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006726 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6727 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006728 return QualType();
6729
6730 // Exactly one GC qualifier difference is allowed: __strong is
6731 // okay if the other type has no GC qualifier but is an Objective
6732 // C object pointer (i.e. implicitly strong by default). We fix
6733 // this by pretending that the unqualified type was actually
6734 // qualified __strong.
6735 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6736 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6737 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6738
6739 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6740 return QualType();
6741
6742 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6743 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6744 }
6745 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6746 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6747 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006748 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006749 }
6750
6751 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006752
Eli Friedman852d63b2009-06-01 01:22:52 +00006753 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6754 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006755
Chris Lattner1adb8832008-01-14 05:45:46 +00006756 // We want to consider the two function types to be the same for these
6757 // comparisons, just force one to the other.
6758 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6759 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006760
6761 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006762 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6763 LHSClass = Type::ConstantArray;
6764 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6765 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006766
John McCallc12c5bb2010-05-15 11:32:37 +00006767 // ObjCInterfaces are just specialized ObjCObjects.
6768 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6769 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6770
Nate Begeman213541a2008-04-18 23:10:10 +00006771 // Canonicalize ExtVector -> Vector.
6772 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6773 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006774
Chris Lattnera36a61f2008-04-07 05:43:21 +00006775 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006776 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006777 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006778 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006779 // Compatibility is based on the underlying type, not the promotion
6780 // type.
John McCall183700f2009-09-21 23:43:11 +00006781 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006782 QualType TINT = ETy->getDecl()->getIntegerType();
6783 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006784 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006785 }
John McCall183700f2009-09-21 23:43:11 +00006786 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006787 QualType TINT = ETy->getDecl()->getIntegerType();
6788 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006789 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006790 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006791 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006792 if (OfBlockPointer && !BlockReturnType) {
6793 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6794 return LHS;
6795 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6796 return RHS;
6797 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006798
Eli Friedman3d815e72008-08-22 00:56:42 +00006799 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006800 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006801
Steve Naroff4a746782008-01-09 22:43:08 +00006802 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006803 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006804#define TYPE(Class, Base)
6805#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006806#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006807#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6808#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6809#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006810 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006811
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006812 case Type::LValueReference:
6813 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006814 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006815 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006816
John McCallc12c5bb2010-05-15 11:32:37 +00006817 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006818 case Type::IncompleteArray:
6819 case Type::VariableArray:
6820 case Type::FunctionProto:
6821 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006822 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006823
Chris Lattner1adb8832008-01-14 05:45:46 +00006824 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006825 {
6826 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006827 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6828 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006829 if (Unqualified) {
6830 LHSPointee = LHSPointee.getUnqualifiedType();
6831 RHSPointee = RHSPointee.getUnqualifiedType();
6832 }
6833 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6834 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006835 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006836 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006837 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006838 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006839 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006840 return getPointerType(ResultType);
6841 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006842 case Type::BlockPointer:
6843 {
6844 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006845 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6846 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006847 if (Unqualified) {
6848 LHSPointee = LHSPointee.getUnqualifiedType();
6849 RHSPointee = RHSPointee.getUnqualifiedType();
6850 }
6851 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6852 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006853 if (ResultType.isNull()) return QualType();
6854 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6855 return LHS;
6856 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6857 return RHS;
6858 return getBlockPointerType(ResultType);
6859 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006860 case Type::Atomic:
6861 {
6862 // Merge two pointer types, while trying to preserve typedef info
6863 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6864 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6865 if (Unqualified) {
6866 LHSValue = LHSValue.getUnqualifiedType();
6867 RHSValue = RHSValue.getUnqualifiedType();
6868 }
6869 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6870 Unqualified);
6871 if (ResultType.isNull()) return QualType();
6872 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6873 return LHS;
6874 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6875 return RHS;
6876 return getAtomicType(ResultType);
6877 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006878 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006879 {
6880 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6881 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6882 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6883 return QualType();
6884
6885 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6886 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006887 if (Unqualified) {
6888 LHSElem = LHSElem.getUnqualifiedType();
6889 RHSElem = RHSElem.getUnqualifiedType();
6890 }
6891
6892 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006893 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006894 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6895 return LHS;
6896 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6897 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006898 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6899 ArrayType::ArraySizeModifier(), 0);
6900 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6901 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006902 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6903 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006904 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6905 return LHS;
6906 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6907 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006908 if (LVAT) {
6909 // FIXME: This isn't correct! But tricky to implement because
6910 // the array's size has to be the size of LHS, but the type
6911 // has to be different.
6912 return LHS;
6913 }
6914 if (RVAT) {
6915 // FIXME: This isn't correct! But tricky to implement because
6916 // the array's size has to be the size of RHS, but the type
6917 // has to be different.
6918 return RHS;
6919 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006920 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6921 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006922 return getIncompleteArrayType(ResultType,
6923 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006924 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006925 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006926 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006927 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006928 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006929 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006930 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006931 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006932 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006933 case Type::Complex:
6934 // Distinct complex types are incompatible.
6935 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006936 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006937 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006938 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6939 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006940 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006941 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006942 case Type::ObjCObject: {
6943 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006944 // FIXME: This should be type compatibility, e.g. whether
6945 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006946 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6947 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6948 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006949 return LHS;
6950
Eli Friedman3d815e72008-08-22 00:56:42 +00006951 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006952 }
Steve Naroff14108da2009-07-10 23:34:53 +00006953 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006954 if (OfBlockPointer) {
6955 if (canAssignObjCInterfacesInBlockPointer(
6956 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006957 RHS->getAs<ObjCObjectPointerType>(),
6958 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006959 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006960 return QualType();
6961 }
John McCall183700f2009-09-21 23:43:11 +00006962 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6963 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006964 return LHS;
6965
Steve Naroffbc76dd02008-12-10 22:14:21 +00006966 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006967 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006968 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006969
David Blaikie7530c032012-01-17 06:56:22 +00006970 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006971}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006972
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006973bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6974 const FunctionProtoType *FromFunctionType,
6975 const FunctionProtoType *ToFunctionType) {
6976 if (FromFunctionType->hasAnyConsumedArgs() !=
6977 ToFunctionType->hasAnyConsumedArgs())
6978 return false;
6979 FunctionProtoType::ExtProtoInfo FromEPI =
6980 FromFunctionType->getExtProtoInfo();
6981 FunctionProtoType::ExtProtoInfo ToEPI =
6982 ToFunctionType->getExtProtoInfo();
6983 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6984 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6985 ArgIdx != NumArgs; ++ArgIdx) {
6986 if (FromEPI.ConsumedArguments[ArgIdx] !=
6987 ToEPI.ConsumedArguments[ArgIdx])
6988 return false;
6989 }
6990 return true;
6991}
6992
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006993/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6994/// 'RHS' attributes and returns the merged version; including for function
6995/// return types.
6996QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6997 QualType LHSCan = getCanonicalType(LHS),
6998 RHSCan = getCanonicalType(RHS);
6999 // If two types are identical, they are compatible.
7000 if (LHSCan == RHSCan)
7001 return LHS;
7002 if (RHSCan->isFunctionType()) {
7003 if (!LHSCan->isFunctionType())
7004 return QualType();
7005 QualType OldReturnType =
7006 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7007 QualType NewReturnType =
7008 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7009 QualType ResReturnType =
7010 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7011 if (ResReturnType.isNull())
7012 return QualType();
7013 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7014 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7015 // In either case, use OldReturnType to build the new function type.
7016 const FunctionType *F = LHS->getAs<FunctionType>();
7017 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007018 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7019 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007020 QualType ResultType
7021 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00007022 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007023 return ResultType;
7024 }
7025 }
7026 return QualType();
7027 }
7028
7029 // If the qualifiers are different, the types can still be merged.
7030 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7031 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7032 if (LQuals != RQuals) {
7033 // If any of these qualifiers are different, we have a type mismatch.
7034 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7035 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7036 return QualType();
7037
7038 // Exactly one GC qualifier difference is allowed: __strong is
7039 // okay if the other type has no GC qualifier but is an Objective
7040 // C object pointer (i.e. implicitly strong by default). We fix
7041 // this by pretending that the unqualified type was actually
7042 // qualified __strong.
7043 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7044 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7045 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7046
7047 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7048 return QualType();
7049
7050 if (GC_L == Qualifiers::Strong)
7051 return LHS;
7052 if (GC_R == Qualifiers::Strong)
7053 return RHS;
7054 return QualType();
7055 }
7056
7057 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7058 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7059 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7060 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7061 if (ResQT == LHSBaseQT)
7062 return LHS;
7063 if (ResQT == RHSBaseQT)
7064 return RHS;
7065 }
7066 return QualType();
7067}
7068
Chris Lattner5426bf62008-04-07 07:01:58 +00007069//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007070// Integer Predicates
7071//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007072
Jay Foad4ba2a172011-01-12 09:06:06 +00007073unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007074 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007075 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007076 if (T->isBooleanType())
7077 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007078 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007079 return (unsigned)getTypeSize(T);
7080}
7081
Abramo Bagnara762f1592012-09-09 10:21:24 +00007082QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007083 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007084
7085 // Turn <4 x signed int> -> <4 x unsigned int>
7086 if (const VectorType *VTy = T->getAs<VectorType>())
7087 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007088 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007089
7090 // For enums, we return the unsigned version of the base type.
7091 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007092 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007093
7094 const BuiltinType *BTy = T->getAs<BuiltinType>();
7095 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007096 switch (BTy->getKind()) {
7097 case BuiltinType::Char_S:
7098 case BuiltinType::SChar:
7099 return UnsignedCharTy;
7100 case BuiltinType::Short:
7101 return UnsignedShortTy;
7102 case BuiltinType::Int:
7103 return UnsignedIntTy;
7104 case BuiltinType::Long:
7105 return UnsignedLongTy;
7106 case BuiltinType::LongLong:
7107 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007108 case BuiltinType::Int128:
7109 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007110 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007111 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007112 }
7113}
7114
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007115ASTMutationListener::~ASTMutationListener() { }
7116
Chris Lattner86df27b2009-06-14 00:45:47 +00007117
7118//===----------------------------------------------------------------------===//
7119// Builtin Type Computation
7120//===----------------------------------------------------------------------===//
7121
7122/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007123/// pointer over the consumed characters. This returns the resultant type. If
7124/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7125/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7126/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007127///
7128/// RequiresICE is filled in on return to indicate whether the value is required
7129/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007130static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007131 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007132 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007133 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007134 // Modifiers.
7135 int HowLong = 0;
7136 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007137 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007138
Chris Lattner33daae62010-10-01 22:42:38 +00007139 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007140 bool Done = false;
7141 while (!Done) {
7142 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007143 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007144 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007145 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007146 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007147 case 'S':
7148 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7149 assert(!Signed && "Can't use 'S' modifier multiple times!");
7150 Signed = true;
7151 break;
7152 case 'U':
7153 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7154 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7155 Unsigned = true;
7156 break;
7157 case 'L':
7158 assert(HowLong <= 2 && "Can't have LLLL modifier");
7159 ++HowLong;
7160 break;
7161 }
7162 }
7163
7164 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007165
Chris Lattner86df27b2009-06-14 00:45:47 +00007166 // Read the base type.
7167 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007168 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007169 case 'v':
7170 assert(HowLong == 0 && !Signed && !Unsigned &&
7171 "Bad modifiers used with 'v'!");
7172 Type = Context.VoidTy;
7173 break;
7174 case 'f':
7175 assert(HowLong == 0 && !Signed && !Unsigned &&
7176 "Bad modifiers used with 'f'!");
7177 Type = Context.FloatTy;
7178 break;
7179 case 'd':
7180 assert(HowLong < 2 && !Signed && !Unsigned &&
7181 "Bad modifiers used with 'd'!");
7182 if (HowLong)
7183 Type = Context.LongDoubleTy;
7184 else
7185 Type = Context.DoubleTy;
7186 break;
7187 case 's':
7188 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7189 if (Unsigned)
7190 Type = Context.UnsignedShortTy;
7191 else
7192 Type = Context.ShortTy;
7193 break;
7194 case 'i':
7195 if (HowLong == 3)
7196 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7197 else if (HowLong == 2)
7198 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7199 else if (HowLong == 1)
7200 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7201 else
7202 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7203 break;
7204 case 'c':
7205 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7206 if (Signed)
7207 Type = Context.SignedCharTy;
7208 else if (Unsigned)
7209 Type = Context.UnsignedCharTy;
7210 else
7211 Type = Context.CharTy;
7212 break;
7213 case 'b': // boolean
7214 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7215 Type = Context.BoolTy;
7216 break;
7217 case 'z': // size_t.
7218 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7219 Type = Context.getSizeType();
7220 break;
7221 case 'F':
7222 Type = Context.getCFConstantStringType();
7223 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007224 case 'G':
7225 Type = Context.getObjCIdType();
7226 break;
7227 case 'H':
7228 Type = Context.getObjCSelType();
7229 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007230 case 'M':
7231 Type = Context.getObjCSuperType();
7232 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007233 case 'a':
7234 Type = Context.getBuiltinVaListType();
7235 assert(!Type.isNull() && "builtin va list type not initialized!");
7236 break;
7237 case 'A':
7238 // This is a "reference" to a va_list; however, what exactly
7239 // this means depends on how va_list is defined. There are two
7240 // different kinds of va_list: ones passed by value, and ones
7241 // passed by reference. An example of a by-value va_list is
7242 // x86, where va_list is a char*. An example of by-ref va_list
7243 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7244 // we want this argument to be a char*&; for x86-64, we want
7245 // it to be a __va_list_tag*.
7246 Type = Context.getBuiltinVaListType();
7247 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007248 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007249 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007250 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007251 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007252 break;
7253 case 'V': {
7254 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007255 unsigned NumElements = strtoul(Str, &End, 10);
7256 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007257 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007258
Chris Lattner14e0e742010-10-01 22:53:11 +00007259 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7260 RequiresICE, false);
7261 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007262
7263 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007264 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007265 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007266 break;
7267 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007268 case 'E': {
7269 char *End;
7270
7271 unsigned NumElements = strtoul(Str, &End, 10);
7272 assert(End != Str && "Missing vector size");
7273
7274 Str = End;
7275
7276 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7277 false);
7278 Type = Context.getExtVectorType(ElementType, NumElements);
7279 break;
7280 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007281 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007282 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7283 false);
7284 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007285 Type = Context.getComplexType(ElementType);
7286 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007287 }
7288 case 'Y' : {
7289 Type = Context.getPointerDiffType();
7290 break;
7291 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007292 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007293 Type = Context.getFILEType();
7294 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007295 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007296 return QualType();
7297 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007298 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007299 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007300 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007301 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007302 else
7303 Type = Context.getjmp_bufType();
7304
Mike Stumpfd612db2009-07-28 23:47:15 +00007305 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007306 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007307 return QualType();
7308 }
7309 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007310 case 'K':
7311 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7312 Type = Context.getucontext_tType();
7313
7314 if (Type.isNull()) {
7315 Error = ASTContext::GE_Missing_ucontext;
7316 return QualType();
7317 }
7318 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007319 case 'p':
7320 Type = Context.getProcessIDType();
7321 break;
Mike Stump782fa302009-07-28 02:25:19 +00007322 }
Mike Stump1eb44332009-09-09 15:08:12 +00007323
Chris Lattner33daae62010-10-01 22:42:38 +00007324 // If there are modifiers and if we're allowed to parse them, go for it.
7325 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007326 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007327 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007328 default: Done = true; --Str; break;
7329 case '*':
7330 case '&': {
7331 // Both pointers and references can have their pointee types
7332 // qualified with an address space.
7333 char *End;
7334 unsigned AddrSpace = strtoul(Str, &End, 10);
7335 if (End != Str && AddrSpace != 0) {
7336 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7337 Str = End;
7338 }
7339 if (c == '*')
7340 Type = Context.getPointerType(Type);
7341 else
7342 Type = Context.getLValueReferenceType(Type);
7343 break;
7344 }
7345 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7346 case 'C':
7347 Type = Type.withConst();
7348 break;
7349 case 'D':
7350 Type = Context.getVolatileType(Type);
7351 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007352 case 'R':
7353 Type = Type.withRestrict();
7354 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007355 }
7356 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007357
Chris Lattner14e0e742010-10-01 22:53:11 +00007358 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007359 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007360
Chris Lattner86df27b2009-06-14 00:45:47 +00007361 return Type;
7362}
7363
7364/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007365QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007366 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007367 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007368 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007369
Chris Lattner5f9e2722011-07-23 10:55:15 +00007370 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007371
Chris Lattner14e0e742010-10-01 22:53:11 +00007372 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007373 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007374 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7375 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007376 if (Error != GE_None)
7377 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007378
7379 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7380
Chris Lattner86df27b2009-06-14 00:45:47 +00007381 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007382 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007383 if (Error != GE_None)
7384 return QualType();
7385
Chris Lattner14e0e742010-10-01 22:53:11 +00007386 // If this argument is required to be an IntegerConstantExpression and the
7387 // caller cares, fill in the bitmask we return.
7388 if (RequiresICE && IntegerConstantArgs)
7389 *IntegerConstantArgs |= 1 << ArgTypes.size();
7390
Chris Lattner86df27b2009-06-14 00:45:47 +00007391 // Do array -> pointer decay. The builtin should use the decayed type.
7392 if (Ty->isArrayType())
7393 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007394
Chris Lattner86df27b2009-06-14 00:45:47 +00007395 ArgTypes.push_back(Ty);
7396 }
7397
7398 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7399 "'.' should only occur at end of builtin type list!");
7400
John McCall00ccbef2010-12-21 00:44:39 +00007401 FunctionType::ExtInfo EI;
7402 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7403
7404 bool Variadic = (TypeStr[0] == '.');
7405
7406 // We really shouldn't be making a no-proto type here, especially in C++.
7407 if (ArgTypes.empty() && Variadic)
7408 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007409
John McCalle23cf432010-12-14 08:05:40 +00007410 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007411 EPI.ExtInfo = EI;
7412 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007413
7414 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007415}
Eli Friedmana95d7572009-08-19 07:44:53 +00007416
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007417GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7418 GVALinkage External = GVA_StrongExternal;
7419
7420 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007421 switch (L) {
7422 case NoLinkage:
7423 case InternalLinkage:
7424 case UniqueExternalLinkage:
7425 return GVA_Internal;
7426
7427 case ExternalLinkage:
7428 switch (FD->getTemplateSpecializationKind()) {
7429 case TSK_Undeclared:
7430 case TSK_ExplicitSpecialization:
7431 External = GVA_StrongExternal;
7432 break;
7433
7434 case TSK_ExplicitInstantiationDefinition:
7435 return GVA_ExplicitTemplateInstantiation;
7436
7437 case TSK_ExplicitInstantiationDeclaration:
7438 case TSK_ImplicitInstantiation:
7439 External = GVA_TemplateInstantiation;
7440 break;
7441 }
7442 }
7443
7444 if (!FD->isInlined())
7445 return External;
7446
David Blaikie4e4d0842012-03-11 07:00:24 +00007447 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007448 // GNU or C99 inline semantics. Determine whether this symbol should be
7449 // externally visible.
7450 if (FD->isInlineDefinitionExternallyVisible())
7451 return External;
7452
7453 // C99 inline semantics, where the symbol is not externally visible.
7454 return GVA_C99Inline;
7455 }
7456
7457 // C++0x [temp.explicit]p9:
7458 // [ Note: The intent is that an inline function that is the subject of
7459 // an explicit instantiation declaration will still be implicitly
7460 // instantiated when used so that the body can be considered for
7461 // inlining, but that no out-of-line copy of the inline function would be
7462 // generated in the translation unit. -- end note ]
7463 if (FD->getTemplateSpecializationKind()
7464 == TSK_ExplicitInstantiationDeclaration)
7465 return GVA_C99Inline;
7466
7467 return GVA_CXXInline;
7468}
7469
7470GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7471 // If this is a static data member, compute the kind of template
7472 // specialization. Otherwise, this variable is not part of a
7473 // template.
7474 TemplateSpecializationKind TSK = TSK_Undeclared;
7475 if (VD->isStaticDataMember())
7476 TSK = VD->getTemplateSpecializationKind();
7477
7478 Linkage L = VD->getLinkage();
Rafael Espindola62a833e2013-01-02 04:19:07 +00007479 assert (!(L == ExternalLinkage && getLangOpts().CPlusPlus &&
7480 VD->getType()->getLinkage() == UniqueExternalLinkage));
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007481
7482 switch (L) {
7483 case NoLinkage:
7484 case InternalLinkage:
7485 case UniqueExternalLinkage:
7486 return GVA_Internal;
7487
7488 case ExternalLinkage:
7489 switch (TSK) {
7490 case TSK_Undeclared:
7491 case TSK_ExplicitSpecialization:
7492 return GVA_StrongExternal;
7493
7494 case TSK_ExplicitInstantiationDeclaration:
7495 llvm_unreachable("Variable should not be instantiated");
7496 // Fall through to treat this like any other instantiation.
7497
7498 case TSK_ExplicitInstantiationDefinition:
7499 return GVA_ExplicitTemplateInstantiation;
7500
7501 case TSK_ImplicitInstantiation:
7502 return GVA_TemplateInstantiation;
7503 }
7504 }
7505
David Blaikie7530c032012-01-17 06:56:22 +00007506 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007507}
7508
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007509bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007510 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7511 if (!VD->isFileVarDecl())
7512 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007513 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007514 return false;
7515
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007516 // Weak references don't produce any output by themselves.
7517 if (D->hasAttr<WeakRefAttr>())
7518 return false;
7519
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007520 // Aliases and used decls are required.
7521 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7522 return true;
7523
7524 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7525 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007526 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007527 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007528
7529 // Constructors and destructors are required.
7530 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7531 return true;
7532
7533 // The key function for a class is required.
7534 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7535 const CXXRecordDecl *RD = MD->getParent();
7536 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7537 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7538 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7539 return true;
7540 }
7541 }
7542
7543 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7544
7545 // static, static inline, always_inline, and extern inline functions can
7546 // always be deferred. Normal inline functions can be deferred in C99/C++.
7547 // Implicit template instantiations can also be deferred in C++.
7548 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007549 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007550 return false;
7551 return true;
7552 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007553
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007554 const VarDecl *VD = cast<VarDecl>(D);
7555 assert(VD->isFileVarDecl() && "Expected file scoped var");
7556
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007557 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7558 return false;
7559
Richard Smith5f9a7e32012-11-12 21:38:00 +00007560 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007561 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007562 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7563 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007564
Richard Smith5f9a7e32012-11-12 21:38:00 +00007565 // Variables that have destruction with side-effects are required.
7566 if (VD->getType().isDestructedType())
7567 return true;
7568
7569 // Variables that have initialization with side-effects are required.
7570 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7571 return true;
7572
7573 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007574}
Charles Davis071cc7d2010-08-16 03:33:14 +00007575
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007576CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007577 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007578 return ABI->getDefaultMethodCallConv(isVariadic);
7579}
7580
7581CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7582 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7583 return CC_Default;
7584 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007585}
7586
Jay Foad4ba2a172011-01-12 09:06:06 +00007587bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007588 // Pass through to the C++ ABI object
7589 return ABI->isNearlyEmpty(RD);
7590}
7591
Peter Collingbourne14110472011-01-13 18:57:25 +00007592MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007593 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007594 case CXXABI_ARM:
7595 case CXXABI_Itanium:
7596 return createItaniumMangleContext(*this, getDiagnostics());
7597 case CXXABI_Microsoft:
7598 return createMicrosoftMangleContext(*this, getDiagnostics());
7599 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007600 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007601}
7602
Charles Davis071cc7d2010-08-16 03:33:14 +00007603CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007604
7605size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007606 return ASTRecordLayouts.getMemorySize()
7607 + llvm::capacity_in_bytes(ObjCLayouts)
7608 + llvm::capacity_in_bytes(KeyFunctions)
7609 + llvm::capacity_in_bytes(ObjCImpls)
7610 + llvm::capacity_in_bytes(BlockVarCopyInits)
7611 + llvm::capacity_in_bytes(DeclAttrs)
7612 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7613 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7614 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7615 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7616 + llvm::capacity_in_bytes(OverriddenMethods)
7617 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007618 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007619 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007620}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007621
David Blaikie66cff722012-11-14 01:52:05 +00007622void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7623 // FIXME: This mangling should be applied to function local classes too
7624 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7625 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7626 return;
7627
7628 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7629 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7630 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7631}
7632
7633int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7634 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7635 UnnamedMangleNumbers.find(Tag);
7636 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7637}
7638
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007639unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7640 CXXRecordDecl *Lambda = CallOperator->getParent();
7641 return LambdaMangleContexts[Lambda->getDeclContext()]
7642 .getManglingNumber(CallOperator);
7643}
7644
7645
Ted Kremenekd211cb72011-10-06 05:00:56 +00007646void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7647 ParamIndices[D] = index;
7648}
7649
7650unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7651 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7652 assert(I != ParamIndices.end() &&
7653 "ParmIndices lacks entry set by ParmVarDecl");
7654 return I->second;
7655}