blob: 9fd40b206d61d950a798e3eef0b5f32e16cfce6e [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"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000016#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000017#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000020#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000021#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000023#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000024#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000026#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000028#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000030#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000031#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000034#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000035#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000036#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000037
Reid Spencer5f016e22007-07-11 17:01:13 +000038using namespace clang;
39
Douglas Gregor18274032010-07-03 00:47:00 +000040unsigned ASTContext::NumImplicitDefaultConstructors;
41unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000042unsigned ASTContext::NumImplicitCopyConstructors;
43unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000044unsigned ASTContext::NumImplicitMoveConstructors;
45unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000046unsigned ASTContext::NumImplicitCopyAssignmentOperators;
47unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveAssignmentOperators;
49unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000050unsigned ASTContext::NumImplicitDestructors;
51unsigned ASTContext::NumImplicitDestructorsDeclared;
52
Reid Spencer5f016e22007-07-11 17:01:13 +000053enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000054 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000055};
56
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000057RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000058 if (!CommentsLoaded && ExternalSource) {
59 ExternalSource->ReadComments();
60 CommentsLoaded = true;
61 }
62
63 assert(D);
64
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000065 // User can not attach documentation to implicit declarations.
66 if (D->isImplicit())
67 return NULL;
68
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000069 // User can not attach documentation to implicit instantiations.
70 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
71 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
72 return NULL;
73 }
74
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000075 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
76 if (VD->isStaticDataMember() &&
77 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
78 return NULL;
79 }
80
81 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
82 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 return NULL;
84 }
85
86 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
87 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 return NULL;
89 }
90
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000091 // TODO: handle comments for function parameters properly.
92 if (isa<ParmVarDecl>(D))
93 return NULL;
94
Dmitri Gribenko96b09862012-07-31 22:37:06 +000095 // TODO: we could look up template parameter documentation in the template
96 // documentation.
97 if (isa<TemplateTypeParmDecl>(D) ||
98 isa<NonTypeTemplateParmDecl>(D) ||
99 isa<TemplateTemplateParmDecl>(D))
100 return NULL;
101
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000102 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000103
104 // If there are no comments anywhere, we won't find anything.
105 if (RawComments.empty())
106 return NULL;
107
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000108 // Find declaration location.
109 // For Objective-C declarations we generally don't expect to have multiple
110 // declarators, thus use declaration starting location as the "declaration
111 // location".
112 // For all other declarations multiple declarators are used quite frequently,
113 // so we use the location of the identifier as the "declaration location".
114 SourceLocation DeclLoc;
115 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000116 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000117 isa<RedeclarableTemplateDecl>(D) ||
118 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000119 DeclLoc = D->getLocStart();
120 else
121 DeclLoc = D->getLocation();
122
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000123 // If the declaration doesn't map directly to a location in a file, we
124 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000125 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
126 return NULL;
127
128 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000129 ArrayRef<RawComment *>::iterator Comment;
130 {
131 // When searching for comments during parsing, the comment we are looking
132 // for is usually among the last two comments we parsed -- check them
133 // first.
134 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
135 BeforeThanCompare<RawComment> Compare(SourceMgr);
136 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
137 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
138 if (!Found && RawComments.size() >= 2) {
139 MaybeBeforeDecl--;
140 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
141 }
142
143 if (Found) {
144 Comment = MaybeBeforeDecl + 1;
145 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
146 &CommentAtDeclLoc, Compare));
147 } else {
148 // Slow path.
149 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
150 &CommentAtDeclLoc, Compare);
151 }
152 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000153
154 // Decompose the location for the declaration and find the beginning of the
155 // file buffer.
156 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
157
158 // First check whether we have a trailing comment.
159 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000160 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000161 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000162 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000163 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000164 // Check that Doxygen trailing comment comes after the declaration, starts
165 // on the same line and in the same file as the declaration.
166 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
167 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
168 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
169 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000170 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000171 }
172 }
173
174 // The comment just after the declaration was not a trailing comment.
175 // Let's look at the previous comment.
176 if (Comment == RawComments.begin())
177 return NULL;
178 --Comment;
179
180 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000181 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000182 return NULL;
183
184 // Decompose the end of the comment.
185 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000186 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000187
188 // If the comment and the declaration aren't in the same file, then they
189 // aren't related.
190 if (DeclLocDecomp.first != CommentEndDecomp.first)
191 return NULL;
192
193 // Get the corresponding buffer.
194 bool Invalid = false;
195 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
196 &Invalid).data();
197 if (Invalid)
198 return NULL;
199
200 // Extract text between the comment and declaration.
201 StringRef Text(Buffer + CommentEndDecomp.second,
202 DeclLocDecomp.second - CommentEndDecomp.second);
203
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000204 // There should be no other declarations or preprocessor directives between
205 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000206 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000207 return NULL;
208
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000209 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000210}
211
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000212namespace {
213/// If we have a 'templated' declaration for a template, adjust 'D' to
214/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000215/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000216const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000217 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000218 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000219 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000220 return FTD;
221
222 // Nothing to do if function is not an implicit instantiation.
223 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
224 return D;
225
226 // Function is an implicit instantiation of a function template?
227 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
228 return FTD;
229
230 // Function is instantiated from a member definition of a class template?
231 if (const FunctionDecl *MemberDecl =
232 FD->getInstantiatedFromMemberFunction())
233 return MemberDecl;
234
235 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000236 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000237 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
238 // Static data member is instantiated from a member definition of a class
239 // template?
240 if (VD->isStaticDataMember())
241 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
242 return MemberDecl;
243
244 return D;
245 }
246 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
247 // Is this class declaration part of a class template?
248 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
249 return CTD;
250
251 // Class is an implicit instantiation of a class template or partial
252 // specialization?
253 if (const ClassTemplateSpecializationDecl *CTSD =
254 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
255 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
256 return D;
257 llvm::PointerUnion<ClassTemplateDecl *,
258 ClassTemplatePartialSpecializationDecl *>
259 PU = CTSD->getSpecializedTemplateOrPartial();
260 return PU.is<ClassTemplateDecl*>() ?
261 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
262 static_cast<const Decl*>(
263 PU.get<ClassTemplatePartialSpecializationDecl *>());
264 }
265
266 // Class is instantiated from a member definition of a class template?
267 if (const MemberSpecializationInfo *Info =
268 CRD->getMemberSpecializationInfo())
269 return Info->getInstantiatedFrom();
270
271 return D;
272 }
273 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
274 // Enum is instantiated from a member definition of a class template?
275 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
276 return MemberDecl;
277
278 return D;
279 }
280 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000281 return D;
282}
283} // unnamed namespace
284
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000285const RawComment *ASTContext::getRawCommentForAnyRedecl(
286 const Decl *D,
287 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000288 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000289
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000290 // Check whether we have cached a comment for this declaration already.
291 {
292 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
293 RedeclComments.find(D);
294 if (Pos != RedeclComments.end()) {
295 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000296 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
297 if (OriginalDecl)
298 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000299 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000300 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000301 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000302 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000303
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000304 // Search for comments attached to declarations in the redeclaration chain.
305 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000306 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000307 for (Decl::redecl_iterator I = D->redecls_begin(),
308 E = D->redecls_end();
309 I != E; ++I) {
310 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
311 RedeclComments.find(*I);
312 if (Pos != RedeclComments.end()) {
313 const RawCommentAndCacheFlags &Raw = Pos->second;
314 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
315 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000316 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000317 break;
318 }
319 } else {
320 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000321 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000322 RawCommentAndCacheFlags Raw;
323 if (RC) {
324 Raw.setRaw(RC);
325 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
326 } else
327 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000328 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000329 RedeclComments[*I] = Raw;
330 if (RC)
331 break;
332 }
333 }
334
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000335 // If we found a comment, it should be a documentation comment.
336 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000337
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000338 if (OriginalDecl)
339 *OriginalDecl = OriginalDeclForRC;
340
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000341 // Update cache for every declaration in the redeclaration chain.
342 RawCommentAndCacheFlags Raw;
343 Raw.setRaw(RC);
344 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000345 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000346
347 for (Decl::redecl_iterator I = D->redecls_begin(),
348 E = D->redecls_end();
349 I != E; ++I) {
350 RawCommentAndCacheFlags &R = RedeclComments[*I];
351 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
352 R = Raw;
353 }
354
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000355 return RC;
356}
357
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000358comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000359 D = adjustDeclToTemplate(D);
360 const Decl *Canonical = D->getCanonicalDecl();
361 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
362 ParsedComments.find(Canonical);
363 if (Pos != ParsedComments.end())
364 return Pos->second;
365
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000366 const Decl *OriginalDecl;
367 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000368 if (!RC)
369 return NULL;
370
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000371 // If the RawComment was attached to other redeclaration of this Decl, we
372 // should parse the comment in context of that other Decl. This is important
373 // because comments can contain references to parameter names which can be
374 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000375 if (D != OriginalDecl)
376 return getCommentForDecl(OriginalDecl);
377
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000378 comments::FullComment *FC = RC->parse(*this, D);
379 ParsedComments[Canonical] = FC;
380 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000381}
382
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000383void
384ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
385 TemplateTemplateParmDecl *Parm) {
386 ID.AddInteger(Parm->getDepth());
387 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000388 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000389
390 TemplateParameterList *Params = Parm->getTemplateParameters();
391 ID.AddInteger(Params->size());
392 for (TemplateParameterList::const_iterator P = Params->begin(),
393 PEnd = Params->end();
394 P != PEnd; ++P) {
395 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
396 ID.AddInteger(0);
397 ID.AddBoolean(TTP->isParameterPack());
398 continue;
399 }
400
401 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
402 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000403 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000404 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000405 if (NTTP->isExpandedParameterPack()) {
406 ID.AddBoolean(true);
407 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000408 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
409 QualType T = NTTP->getExpansionType(I);
410 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
411 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000412 } else
413 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000414 continue;
415 }
416
417 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
418 ID.AddInteger(2);
419 Profile(ID, TTP);
420 }
421}
422
423TemplateTemplateParmDecl *
424ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000425 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000426 // Check if we already have a canonical template template parameter.
427 llvm::FoldingSetNodeID ID;
428 CanonicalTemplateTemplateParm::Profile(ID, TTP);
429 void *InsertPos = 0;
430 CanonicalTemplateTemplateParm *Canonical
431 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
432 if (Canonical)
433 return Canonical->getParam();
434
435 // Build a canonical template parameter list.
436 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000438 CanonParams.reserve(Params->size());
439 for (TemplateParameterList::const_iterator P = Params->begin(),
440 PEnd = Params->end();
441 P != PEnd; ++P) {
442 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
443 CanonParams.push_back(
444 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000445 SourceLocation(),
446 SourceLocation(),
447 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000448 TTP->getIndex(), 0, false,
449 TTP->isParameterPack()));
450 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000451 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
452 QualType T = getCanonicalType(NTTP->getType());
453 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
454 NonTypeTemplateParmDecl *Param;
455 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000456 SmallVector<QualType, 2> ExpandedTypes;
457 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000458 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
459 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
460 ExpandedTInfos.push_back(
461 getTrivialTypeSourceInfo(ExpandedTypes.back()));
462 }
463
464 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000465 SourceLocation(),
466 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000467 NTTP->getDepth(),
468 NTTP->getPosition(), 0,
469 T,
470 TInfo,
471 ExpandedTypes.data(),
472 ExpandedTypes.size(),
473 ExpandedTInfos.data());
474 } else {
475 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000476 SourceLocation(),
477 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000478 NTTP->getDepth(),
479 NTTP->getPosition(), 0,
480 T,
481 NTTP->isParameterPack(),
482 TInfo);
483 }
484 CanonParams.push_back(Param);
485
486 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000487 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
488 cast<TemplateTemplateParmDecl>(*P)));
489 }
490
491 TemplateTemplateParmDecl *CanonTTP
492 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
493 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000494 TTP->getPosition(),
495 TTP->isParameterPack(),
496 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000497 TemplateParameterList::Create(*this, SourceLocation(),
498 SourceLocation(),
499 CanonParams.data(),
500 CanonParams.size(),
501 SourceLocation()));
502
503 // Get the new insert position for the node we care about.
504 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
505 assert(Canonical == 0 && "Shouldn't be in the map!");
506 (void)Canonical;
507
508 // Create the canonical template template parameter entry.
509 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
510 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
511 return CanonTTP;
512}
513
Charles Davis071cc7d2010-08-16 03:33:14 +0000514CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000515 if (!LangOpts.CPlusPlus) return 0;
516
Charles Davis20cf7172010-08-19 02:18:14 +0000517 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000518 case CXXABI_ARM:
519 return CreateARMCXXABI(*this);
520 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000521 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000522 case CXXABI_Microsoft:
523 return CreateMicrosoftCXXABI(*this);
524 }
David Blaikie7530c032012-01-17 06:56:22 +0000525 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000526}
527
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000528static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000529 const LangOptions &LOpts) {
530 if (LOpts.FakeAddressSpaceMap) {
531 // The fake address space map must have a distinct entry for each
532 // language-specific address space.
533 static const unsigned FakeAddrSpaceMap[] = {
534 1, // opencl_global
535 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000536 3, // opencl_constant
537 4, // cuda_device
538 5, // cuda_constant
539 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000540 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000541 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000542 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000543 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000544 }
545}
546
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000547ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000548 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000549 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000550 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000551 unsigned size_reserve,
552 bool DelayInitialization)
553 : FunctionProtoTypes(this_()),
554 TemplateSpecializationTypes(this_()),
555 DependentTemplateSpecializationTypes(this_()),
556 SubstTemplateTemplateParmPacks(this_()),
557 GlobalNestedNameSpecifier(0),
558 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000559 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000560 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000561 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000562 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000563 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000564 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
565 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
566 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000567 NullTypeSourceInfo(QualType()),
568 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000569 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000570 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000571 Idents(idents), Selectors(sels),
572 BuiltinInfo(builtins),
573 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000574 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000575 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000576 CommentCommandTraits(BumpAlloc),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000577 LastSDM(0, 0),
578 UniqueBlockByRefTypeID(0)
579{
Mike Stump1eb44332009-09-09 15:08:12 +0000580 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000581 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000582
583 if (!DelayInitialization) {
584 assert(t && "No target supplied for ASTContext initialization");
585 InitBuiltinTypes(*t);
586 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000587}
588
Reid Spencer5f016e22007-07-11 17:01:13 +0000589ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000590 // Release the DenseMaps associated with DeclContext objects.
591 // FIXME: Is this the ideal solution?
592 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000593
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000594 // Call all of the deallocation functions.
595 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
596 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000597
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000598 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000599 // because they can contain DenseMaps.
600 for (llvm::DenseMap<const ObjCContainerDecl*,
601 const ASTRecordLayout*>::iterator
602 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
603 // Increment in loop to prevent using deallocated memory.
604 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
605 R->Destroy(*this);
606
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000607 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
608 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
609 // Increment in loop to prevent using deallocated memory.
610 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
611 R->Destroy(*this);
612 }
Douglas Gregor63200642010-08-30 16:49:28 +0000613
614 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
615 AEnd = DeclAttrs.end();
616 A != AEnd; ++A)
617 A->second->~AttrVec();
618}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000619
Douglas Gregor00545312010-05-23 18:26:36 +0000620void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
621 Deallocations.push_back(std::make_pair(Callback, Data));
622}
623
Mike Stump1eb44332009-09-09 15:08:12 +0000624void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000625ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000626 ExternalSource.reset(Source.take());
627}
628
Reid Spencer5f016e22007-07-11 17:01:13 +0000629void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000630 llvm::errs() << "\n*** AST Context Stats:\n";
631 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000632
Douglas Gregordbe833d2009-05-26 14:40:08 +0000633 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000634#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000635#define ABSTRACT_TYPE(Name, Parent)
636#include "clang/AST/TypeNodes.def"
637 0 // Extra
638 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000639
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
641 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000642 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 }
644
Douglas Gregordbe833d2009-05-26 14:40:08 +0000645 unsigned Idx = 0;
646 unsigned TotalBytes = 0;
647#define TYPE(Name, Parent) \
648 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000649 llvm::errs() << " " << counts[Idx] << " " << #Name \
650 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000651 TotalBytes += counts[Idx] * sizeof(Name##Type); \
652 ++Idx;
653#define ABSTRACT_TYPE(Name, Parent)
654#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Chandler Carruthcd92a652011-07-04 05:32:14 +0000656 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
657
Douglas Gregor4923aa22010-07-02 20:37:36 +0000658 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000659 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
660 << NumImplicitDefaultConstructors
661 << " implicit default constructors created\n";
662 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
663 << NumImplicitCopyConstructors
664 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000665 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000666 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
667 << NumImplicitMoveConstructors
668 << " implicit move constructors created\n";
669 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
670 << NumImplicitCopyAssignmentOperators
671 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000672 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000673 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
674 << NumImplicitMoveAssignmentOperators
675 << " implicit move assignment operators created\n";
676 llvm::errs() << NumImplicitDestructorsDeclared << "/"
677 << NumImplicitDestructors
678 << " implicit destructors created\n";
679
Douglas Gregor2cf26342009-04-09 22:27:44 +0000680 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000681 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000682 ExternalSource->PrintStats();
683 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000684
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000685 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000686}
687
Douglas Gregor772eeae2011-08-12 06:49:56 +0000688TypedefDecl *ASTContext::getInt128Decl() const {
689 if (!Int128Decl) {
690 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
691 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
692 getTranslationUnitDecl(),
693 SourceLocation(),
694 SourceLocation(),
695 &Idents.get("__int128_t"),
696 TInfo);
697 }
698
699 return Int128Decl;
700}
701
702TypedefDecl *ASTContext::getUInt128Decl() const {
703 if (!UInt128Decl) {
704 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
705 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
706 getTranslationUnitDecl(),
707 SourceLocation(),
708 SourceLocation(),
709 &Idents.get("__uint128_t"),
710 TInfo);
711 }
712
713 return UInt128Decl;
714}
Reid Spencer5f016e22007-07-11 17:01:13 +0000715
John McCalle27ec8a2009-10-23 23:03:21 +0000716void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000717 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000718 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000719 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000720}
721
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000722void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
723 assert((!this->Target || this->Target == &Target) &&
724 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000727 this->Target = &Target;
728
729 ABI.reset(createCXXABI(Target));
730 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
731
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 // C99 6.2.5p19.
733 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 // C99 6.2.5p2.
736 InitBuiltinType(BoolTy, BuiltinType::Bool);
737 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000738 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 InitBuiltinType(CharTy, BuiltinType::Char_S);
740 else
741 InitBuiltinType(CharTy, BuiltinType::Char_U);
742 // C99 6.2.5p4.
743 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
744 InitBuiltinType(ShortTy, BuiltinType::Short);
745 InitBuiltinType(IntTy, BuiltinType::Int);
746 InitBuiltinType(LongTy, BuiltinType::Long);
747 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 // C99 6.2.5p6.
750 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
751 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
752 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
753 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
754 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 // C99 6.2.5p10.
757 InitBuiltinType(FloatTy, BuiltinType::Float);
758 InitBuiltinType(DoubleTy, BuiltinType::Double);
759 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000760
Chris Lattner2df9ced2009-04-30 02:43:43 +0000761 // GNU extension, 128-bit integers.
762 InitBuiltinType(Int128Ty, BuiltinType::Int128);
763 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
764
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000765 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000766 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000767 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
768 else // -fshort-wchar makes wchar_t be unsigned.
769 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000770 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000771 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000772
James Molloy392da482012-05-04 10:55:22 +0000773 WIntTy = getFromTargetType(Target.getWIntType());
774
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000775 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
776 InitBuiltinType(Char16Ty, BuiltinType::Char16);
777 else // C99
778 Char16Ty = getFromTargetType(Target.getChar16Type());
779
780 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
781 InitBuiltinType(Char32Ty, BuiltinType::Char32);
782 else // C99
783 Char32Ty = getFromTargetType(Target.getChar32Type());
784
Douglas Gregor898574e2008-12-05 23:32:09 +0000785 // Placeholder type for type-dependent expressions whose type is
786 // completely unknown. No code should ever check a type against
787 // DependentTy and users should never see it; however, it is here to
788 // help diagnose failures to properly check for type-dependent
789 // expressions.
790 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000791
John McCall2a984ca2010-10-12 00:20:44 +0000792 // Placeholder type for functions.
793 InitBuiltinType(OverloadTy, BuiltinType::Overload);
794
John McCall864c0412011-04-26 20:42:42 +0000795 // Placeholder type for bound members.
796 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
797
John McCall3c3b7f92011-10-25 17:37:35 +0000798 // Placeholder type for pseudo-objects.
799 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
800
John McCall1de4d4e2011-04-07 08:22:57 +0000801 // "any" type; useful for debugger-like clients.
802 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
803
John McCall0ddaeb92011-10-17 18:09:15 +0000804 // Placeholder type for unbridged ARC casts.
805 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
806
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000807 // Placeholder type for builtin functions.
808 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
809
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 // C99 6.2.5p11.
811 FloatComplexTy = getComplexType(FloatTy);
812 DoubleComplexTy = getComplexType(DoubleTy);
813 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000814
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000815 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000816 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
817 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000818 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000819
820 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000821 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
822 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000823
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000824 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000826 // void * type
827 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000828
829 // nullptr type (C++0x 2.14.7)
830 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000831
832 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
833 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000834
835 // Builtin type used to help define __builtin_va_list.
836 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000837}
838
David Blaikied6471f72011-09-25 23:23:43 +0000839DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000840 return SourceMgr.getDiagnostics();
841}
842
Douglas Gregor63200642010-08-30 16:49:28 +0000843AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
844 AttrVec *&Result = DeclAttrs[D];
845 if (!Result) {
846 void *Mem = Allocate(sizeof(AttrVec));
847 Result = new (Mem) AttrVec;
848 }
849
850 return *Result;
851}
852
853/// \brief Erase the attributes corresponding to the given declaration.
854void ASTContext::eraseDeclAttrs(const Decl *D) {
855 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
856 if (Pos != DeclAttrs.end()) {
857 Pos->second->~AttrVec();
858 DeclAttrs.erase(Pos);
859 }
860}
861
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000862MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000863ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000864 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000865 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000866 = InstantiatedFromStaticDataMember.find(Var);
867 if (Pos == InstantiatedFromStaticDataMember.end())
868 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Douglas Gregor7caa6822009-07-24 20:34:43 +0000870 return Pos->second;
871}
872
Mike Stump1eb44332009-09-09 15:08:12 +0000873void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000874ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000875 TemplateSpecializationKind TSK,
876 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000877 assert(Inst->isStaticDataMember() && "Not a static data member");
878 assert(Tmpl->isStaticDataMember() && "Not a static data member");
879 assert(!InstantiatedFromStaticDataMember[Inst] &&
880 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000881 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000882 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000883}
884
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000885FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
886 const FunctionDecl *FD){
887 assert(FD && "Specialization is 0");
888 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000889 = ClassScopeSpecializationPattern.find(FD);
890 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000891 return 0;
892
893 return Pos->second;
894}
895
896void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
897 FunctionDecl *Pattern) {
898 assert(FD && "Specialization is 0");
899 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000900 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000901}
902
John McCall7ba107a2009-11-18 02:36:19 +0000903NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000904ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000905 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000906 = InstantiatedFromUsingDecl.find(UUD);
907 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000908 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Anders Carlsson0d8df782009-08-29 19:37:28 +0000910 return Pos->second;
911}
912
913void
John McCalled976492009-12-04 22:46:56 +0000914ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
915 assert((isa<UsingDecl>(Pattern) ||
916 isa<UnresolvedUsingValueDecl>(Pattern) ||
917 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
918 "pattern decl is not a using decl");
919 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
920 InstantiatedFromUsingDecl[Inst] = Pattern;
921}
922
923UsingShadowDecl *
924ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
925 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
926 = InstantiatedFromUsingShadowDecl.find(Inst);
927 if (Pos == InstantiatedFromUsingShadowDecl.end())
928 return 0;
929
930 return Pos->second;
931}
932
933void
934ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
935 UsingShadowDecl *Pattern) {
936 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
937 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000938}
939
Anders Carlssond8b285f2009-09-01 04:26:58 +0000940FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
941 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
942 = InstantiatedFromUnnamedFieldDecl.find(Field);
943 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
944 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Anders Carlssond8b285f2009-09-01 04:26:58 +0000946 return Pos->second;
947}
948
949void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
950 FieldDecl *Tmpl) {
951 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
952 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
953 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
954 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Anders Carlssond8b285f2009-09-01 04:26:58 +0000956 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
957}
958
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000959bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
960 const FieldDecl *LastFD) const {
961 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000962 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000963}
964
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000965bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
966 const FieldDecl *LastFD) const {
967 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000968 FD->getBitWidthValue(*this) == 0 &&
969 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000970}
971
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000972bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
973 const FieldDecl *LastFD) const {
974 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000975 FD->getBitWidthValue(*this) &&
976 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000977}
978
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000979bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000980 const FieldDecl *LastFD) const {
981 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000982 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000983}
984
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000985bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000986 const FieldDecl *LastFD) const {
987 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000988 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000989}
990
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000991ASTContext::overridden_cxx_method_iterator
992ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
993 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
994 = OverriddenMethods.find(Method);
995 if (Pos == OverriddenMethods.end())
996 return 0;
997
998 return Pos->second.begin();
999}
1000
1001ASTContext::overridden_cxx_method_iterator
1002ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1003 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1004 = OverriddenMethods.find(Method);
1005 if (Pos == OverriddenMethods.end())
1006 return 0;
1007
1008 return Pos->second.end();
1009}
1010
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001011unsigned
1012ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1013 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1014 = OverriddenMethods.find(Method);
1015 if (Pos == OverriddenMethods.end())
1016 return 0;
1017
1018 return Pos->second.size();
1019}
1020
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001021void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1022 const CXXMethodDecl *Overridden) {
1023 OverriddenMethods[Method].push_back(Overridden);
1024}
1025
Douglas Gregore6649772011-12-03 00:30:27 +00001026void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1027 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1028 assert(!Import->isFromASTFile() && "Non-local import declaration");
1029 if (!FirstLocalImport) {
1030 FirstLocalImport = Import;
1031 LastLocalImport = Import;
1032 return;
1033 }
1034
1035 LastLocalImport->NextLocalImport = Import;
1036 LastLocalImport = Import;
1037}
1038
Chris Lattner464175b2007-07-18 17:52:12 +00001039//===----------------------------------------------------------------------===//
1040// Type Sizing and Analysis
1041//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001042
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001043/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1044/// scalar floating point type.
1045const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001046 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001047 assert(BT && "Not a floating point type!");
1048 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001049 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001050 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001051 case BuiltinType::Float: return Target->getFloatFormat();
1052 case BuiltinType::Double: return Target->getDoubleFormat();
1053 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001054 }
1055}
1056
Ken Dyck8b752f12010-01-27 17:10:57 +00001057/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001058/// specified decl. Note that bitfields do not have a valid alignment, so
1059/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001060/// If @p RefAsPointee, references are treated like their underlying type
1061/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001062CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001063 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001064
John McCall4081a5c2010-10-08 18:24:19 +00001065 bool UseAlignAttrOnly = false;
1066 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1067 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001068
John McCall4081a5c2010-10-08 18:24:19 +00001069 // __attribute__((aligned)) can increase or decrease alignment
1070 // *except* on a struct or struct member, where it only increases
1071 // alignment unless 'packed' is also specified.
1072 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001073 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001074 // ignore that possibility; Sema should diagnose it.
1075 if (isa<FieldDecl>(D)) {
1076 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1077 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1078 } else {
1079 UseAlignAttrOnly = true;
1080 }
1081 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001082 else if (isa<FieldDecl>(D))
1083 UseAlignAttrOnly =
1084 D->hasAttr<PackedAttr>() ||
1085 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001086
John McCallba4f5d52011-01-20 07:57:12 +00001087 // If we're using the align attribute only, just ignore everything
1088 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001089 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001090 // do nothing
1091
John McCall4081a5c2010-10-08 18:24:19 +00001092 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001093 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001094 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001095 if (RefAsPointee)
1096 T = RT->getPointeeType();
1097 else
1098 T = getPointerType(RT->getPointeeType());
1099 }
1100 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001101 // Adjust alignments of declarations with array type by the
1102 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001103 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001104 const ArrayType *arrayType;
1105 if (MinWidth && (arrayType = getAsArrayType(T))) {
1106 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001107 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001108 else if (isa<ConstantArrayType>(arrayType) &&
1109 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001110 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001111
John McCall3b657512011-01-19 10:06:00 +00001112 // Walk through any array types while we're at it.
1113 T = getBaseElementType(arrayType);
1114 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001115 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001116 }
John McCallba4f5d52011-01-20 07:57:12 +00001117
1118 // Fields can be subject to extra alignment constraints, like if
1119 // the field is packed, the struct is packed, or the struct has a
1120 // a max-field-alignment constraint (#pragma pack). So calculate
1121 // the actual alignment of the field within the struct, and then
1122 // (as we're expected to) constrain that by the alignment of the type.
1123 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1124 // So calculate the alignment of the field.
1125 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1126
1127 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001128 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001129
1130 // Use the GCD of that and the offset within the record.
1131 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1132 if (offset > 0) {
1133 // Alignment is always a power of 2, so the GCD will be a power of 2,
1134 // which means we get to do this crazy thing instead of Euclid's.
1135 uint64_t lowBitOfOffset = offset & (~offset + 1);
1136 if (lowBitOfOffset < fieldAlign)
1137 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1138 }
1139
1140 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001141 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001142 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001143
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001144 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001145}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001146
John McCall929bbfb2012-08-21 04:10:00 +00001147// getTypeInfoDataSizeInChars - Return the size of a type, in
1148// chars. If the type is a record, its data size is returned. This is
1149// the size of the memcpy that's performed when assigning this type
1150// using a trivial copy/move assignment operator.
1151std::pair<CharUnits, CharUnits>
1152ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1153 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1154
1155 // In C++, objects can sometimes be allocated into the tail padding
1156 // of a base-class subobject. We decide whether that's possible
1157 // during class layout, so here we can just trust the layout results.
1158 if (getLangOpts().CPlusPlus) {
1159 if (const RecordType *RT = T->getAs<RecordType>()) {
1160 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1161 sizeAndAlign.first = layout.getDataSize();
1162 }
1163 }
1164
1165 return sizeAndAlign;
1166}
1167
John McCallea1471e2010-05-20 01:18:31 +00001168std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001169ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001170 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001171 return std::make_pair(toCharUnitsFromBits(Info.first),
1172 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001173}
1174
1175std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001176ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001177 return getTypeInfoInChars(T.getTypePtr());
1178}
1179
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001180std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1181 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1182 if (it != MemoizedTypeInfo.end())
1183 return it->second;
1184
1185 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1186 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1187 return Info;
1188}
1189
1190/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1191/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001192///
1193/// FIXME: Pointers into different addr spaces could have different sizes and
1194/// alignment requirements: getPointerInfo should take an AddrSpace, this
1195/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001196std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001197ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001198 uint64_t Width=0;
1199 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001200 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001201#define TYPE(Class, Base)
1202#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001203#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001204#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1205#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001206 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001207
Chris Lattner692233e2007-07-13 22:27:08 +00001208 case Type::FunctionNoProto:
1209 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001210 // GCC extension: alignof(function) = 32 bits
1211 Width = 0;
1212 Align = 32;
1213 break;
1214
Douglas Gregor72564e72009-02-26 23:50:07 +00001215 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001216 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001217 Width = 0;
1218 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1219 break;
1220
Steve Narofffb22d962007-08-30 01:06:46 +00001221 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001222 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattner98be4942008-03-05 18:54:05 +00001224 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001225 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001226 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1227 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001228 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001229 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001230 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001231 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001232 }
Nate Begeman213541a2008-04-18 23:10:10 +00001233 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001234 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001235 const VectorType *VT = cast<VectorType>(T);
1236 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1237 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001238 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001239 // If the alignment is not a power of 2, round up to the next power of 2.
1240 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001241 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001242 Align = llvm::NextPowerOf2(Align);
1243 Width = llvm::RoundUpToAlignment(Width, Align);
1244 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001245 // Adjust the alignment based on the target max.
1246 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1247 if (TargetVectorAlign && TargetVectorAlign < Align)
1248 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001249 break;
1250 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001251
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001252 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001253 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001254 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001255 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001256 // GCC extension: alignof(void) = 8 bits.
1257 Width = 0;
1258 Align = 8;
1259 break;
1260
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001261 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001262 Width = Target->getBoolWidth();
1263 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001264 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001265 case BuiltinType::Char_S:
1266 case BuiltinType::Char_U:
1267 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001268 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001269 Width = Target->getCharWidth();
1270 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001271 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001272 case BuiltinType::WChar_S:
1273 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001274 Width = Target->getWCharWidth();
1275 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001276 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001277 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001278 Width = Target->getChar16Width();
1279 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001280 break;
1281 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001282 Width = Target->getChar32Width();
1283 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001284 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001285 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001286 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001287 Width = Target->getShortWidth();
1288 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001289 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001290 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001291 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001292 Width = Target->getIntWidth();
1293 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001294 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001295 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001296 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001297 Width = Target->getLongWidth();
1298 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001299 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001300 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001301 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001302 Width = Target->getLongLongWidth();
1303 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001304 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001305 case BuiltinType::Int128:
1306 case BuiltinType::UInt128:
1307 Width = 128;
1308 Align = 128; // int128_t is 128-bit aligned on all targets.
1309 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001310 case BuiltinType::Half:
1311 Width = Target->getHalfWidth();
1312 Align = Target->getHalfAlign();
1313 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001314 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001315 Width = Target->getFloatWidth();
1316 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001317 break;
1318 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001319 Width = Target->getDoubleWidth();
1320 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001321 break;
1322 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001323 Width = Target->getLongDoubleWidth();
1324 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001325 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001326 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001327 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1328 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001329 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001330 case BuiltinType::ObjCId:
1331 case BuiltinType::ObjCClass:
1332 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001333 Width = Target->getPointerWidth(0);
1334 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001335 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001336 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001337 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001338 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001339 Width = Target->getPointerWidth(0);
1340 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001341 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001342 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001343 unsigned AS = getTargetAddressSpace(
1344 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001345 Width = Target->getPointerWidth(AS);
1346 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001347 break;
1348 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001349 case Type::LValueReference:
1350 case Type::RValueReference: {
1351 // alignof and sizeof should never enter this code path here, so we go
1352 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001353 unsigned AS = getTargetAddressSpace(
1354 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001355 Width = Target->getPointerWidth(AS);
1356 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001357 break;
1358 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001359 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001360 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001361 Width = Target->getPointerWidth(AS);
1362 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001363 break;
1364 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001365 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001366 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001367 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001368 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001369 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001370 Align = PtrDiffInfo.second;
1371 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001372 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001373 case Type::Complex: {
1374 // Complex types have the same alignment as their elements, but twice the
1375 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001376 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001377 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001378 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001379 Align = EltInfo.second;
1380 break;
1381 }
John McCallc12c5bb2010-05-15 11:32:37 +00001382 case Type::ObjCObject:
1383 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001384 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001385 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001386 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001387 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001388 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001389 break;
1390 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001391 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001392 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001393 const TagType *TT = cast<TagType>(T);
1394
1395 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001396 Width = 8;
1397 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001398 break;
1399 }
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Daniel Dunbar1d751182008-11-08 05:48:37 +00001401 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001402 return getTypeInfo(ET->getDecl()->getIntegerType());
1403
Daniel Dunbar1d751182008-11-08 05:48:37 +00001404 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001405 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001406 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001407 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001408 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001409 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001410
Chris Lattner9fcfe922009-10-22 05:17:15 +00001411 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001412 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1413 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001414
Richard Smith34b41d92011-02-20 03:19:35 +00001415 case Type::Auto: {
1416 const AutoType *A = cast<AutoType>(T);
1417 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001418 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001419 }
1420
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001421 case Type::Paren:
1422 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1423
Douglas Gregor18857642009-04-30 17:32:17 +00001424 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001425 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001426 std::pair<uint64_t, unsigned> Info
1427 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001428 // If the typedef has an aligned attribute on it, it overrides any computed
1429 // alignment we have. This violates the GCC documentation (which says that
1430 // attribute(aligned) can only round up) but matches its implementation.
1431 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1432 Align = AttrAlign;
1433 else
1434 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001435 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001436 break;
Chris Lattner71763312008-04-06 22:05:18 +00001437 }
Douglas Gregor18857642009-04-30 17:32:17 +00001438
1439 case Type::TypeOfExpr:
1440 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1441 .getTypePtr());
1442
1443 case Type::TypeOf:
1444 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1445
Anders Carlsson395b4752009-06-24 19:06:50 +00001446 case Type::Decltype:
1447 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1448 .getTypePtr());
1449
Sean Huntca63c202011-05-24 22:41:36 +00001450 case Type::UnaryTransform:
1451 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1452
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001453 case Type::Elaborated:
1454 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001455
John McCall9d156a72011-01-06 01:58:22 +00001456 case Type::Attributed:
1457 return getTypeInfo(
1458 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1459
Richard Smith3e4c6c42011-05-05 21:57:07 +00001460 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001461 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001462 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001463 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1464 // A type alias template specialization may refer to a typedef with the
1465 // aligned attribute on it.
1466 if (TST->isTypeAlias())
1467 return getTypeInfo(TST->getAliasedType().getTypePtr());
1468 else
1469 return getTypeInfo(getCanonicalType(T));
1470 }
1471
Eli Friedmanb001de72011-10-06 23:00:33 +00001472 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001473 std::pair<uint64_t, unsigned> Info
1474 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1475 Width = Info.first;
1476 Align = Info.second;
1477 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1478 llvm::isPowerOf2_64(Width)) {
1479 // We can potentially perform lock-free atomic operations for this
1480 // type; promote the alignment appropriately.
1481 // FIXME: We could potentially promote the width here as well...
1482 // is that worthwhile? (Non-struct atomic types generally have
1483 // power-of-two size anyway, but structs might not. Requires a bit
1484 // of implementation work to make sure we zero out the extra bits.)
1485 Align = static_cast<unsigned>(Width);
1486 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001487 }
1488
Douglas Gregor18857642009-04-30 17:32:17 +00001489 }
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Eli Friedman2be46072011-10-14 20:59:01 +00001491 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001492 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001493}
1494
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001495/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1496CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1497 return CharUnits::fromQuantity(BitSize / getCharWidth());
1498}
1499
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001500/// toBits - Convert a size in characters to a size in characters.
1501int64_t ASTContext::toBits(CharUnits CharSize) const {
1502 return CharSize.getQuantity() * getCharWidth();
1503}
1504
Ken Dyckbdc601b2009-12-22 14:23:30 +00001505/// getTypeSizeInChars - Return the size of the specified type, in characters.
1506/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001507CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001508 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001509}
Jay Foad4ba2a172011-01-12 09:06:06 +00001510CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001511 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001512}
1513
Ken Dyck16e20cc2010-01-26 17:25:18 +00001514/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001515/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001516CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001517 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001518}
Jay Foad4ba2a172011-01-12 09:06:06 +00001519CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001520 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001521}
1522
Chris Lattner34ebde42009-01-27 18:08:34 +00001523/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1524/// type for the current target in bits. This can be different than the ABI
1525/// alignment in cases where it is beneficial for performance to overalign
1526/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001527unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001528 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001529
1530 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001531 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001532 T = CT->getElementType().getTypePtr();
1533 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001534 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1535 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001536 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1537
Chris Lattner34ebde42009-01-27 18:08:34 +00001538 return ABIAlign;
1539}
1540
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001541/// DeepCollectObjCIvars -
1542/// This routine first collects all declared, but not synthesized, ivars in
1543/// super class and then collects all ivars, including those synthesized for
1544/// current class. This routine is used for implementation of current class
1545/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001546///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001547void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1548 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001549 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001550 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1551 DeepCollectObjCIvars(SuperClass, false, Ivars);
1552 if (!leafClass) {
1553 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1554 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001555 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001556 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001557 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001558 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001559 Iv= Iv->getNextIvar())
1560 Ivars.push_back(Iv);
1561 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001562}
1563
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001564/// CollectInheritedProtocols - Collect all protocols in current class and
1565/// those inherited by it.
1566void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001567 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001568 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001569 // We can use protocol_iterator here instead of
1570 // all_referenced_protocol_iterator since we are walking all categories.
1571 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1572 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001573 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001574 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001575 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001576 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001577 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001578 CollectInheritedProtocols(*P, Protocols);
1579 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001580 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001581
1582 // Categories of this Interface.
1583 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1584 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1585 CollectInheritedProtocols(CDeclChain, Protocols);
1586 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1587 while (SD) {
1588 CollectInheritedProtocols(SD, Protocols);
1589 SD = SD->getSuperClass();
1590 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001591 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001592 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001593 PE = OC->protocol_end(); P != PE; ++P) {
1594 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001595 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001596 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1597 PE = Proto->protocol_end(); P != PE; ++P)
1598 CollectInheritedProtocols(*P, Protocols);
1599 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001600 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001601 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1602 PE = OP->protocol_end(); P != PE; ++P) {
1603 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001604 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001605 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1606 PE = Proto->protocol_end(); P != PE; ++P)
1607 CollectInheritedProtocols(*P, Protocols);
1608 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001609 }
1610}
1611
Jay Foad4ba2a172011-01-12 09:06:06 +00001612unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001613 unsigned count = 0;
1614 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001615 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1616 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001617 count += CDecl->ivar_size();
1618
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001619 // Count ivar defined in this class's implementation. This
1620 // includes synthesized ivars.
1621 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001622 count += ImplDecl->ivar_size();
1623
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001624 return count;
1625}
1626
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001627bool ASTContext::isSentinelNullExpr(const Expr *E) {
1628 if (!E)
1629 return false;
1630
1631 // nullptr_t is always treated as null.
1632 if (E->getType()->isNullPtrType()) return true;
1633
1634 if (E->getType()->isAnyPointerType() &&
1635 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1636 Expr::NPC_ValueDependentIsNull))
1637 return true;
1638
1639 // Unfortunately, __null has type 'int'.
1640 if (isa<GNUNullExpr>(E)) return true;
1641
1642 return false;
1643}
1644
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001645/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1646ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1647 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1648 I = ObjCImpls.find(D);
1649 if (I != ObjCImpls.end())
1650 return cast<ObjCImplementationDecl>(I->second);
1651 return 0;
1652}
1653/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1654ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1655 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1656 I = ObjCImpls.find(D);
1657 if (I != ObjCImpls.end())
1658 return cast<ObjCCategoryImplDecl>(I->second);
1659 return 0;
1660}
1661
1662/// \brief Set the implementation of ObjCInterfaceDecl.
1663void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1664 ObjCImplementationDecl *ImplD) {
1665 assert(IFaceD && ImplD && "Passed null params");
1666 ObjCImpls[IFaceD] = ImplD;
1667}
1668/// \brief Set the implementation of ObjCCategoryDecl.
1669void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1670 ObjCCategoryImplDecl *ImplD) {
1671 assert(CatD && ImplD && "Passed null params");
1672 ObjCImpls[CatD] = ImplD;
1673}
1674
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001675ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1676 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1677 return ID;
1678 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1679 return CD->getClassInterface();
1680 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1681 return IMD->getClassInterface();
1682
1683 return 0;
1684}
1685
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001686/// \brief Get the copy initialization expression of VarDecl,or NULL if
1687/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001688Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001689 assert(VD && "Passed null params");
1690 assert(VD->hasAttr<BlocksAttr>() &&
1691 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001692 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001693 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001694 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1695}
1696
1697/// \brief Set the copy inialization expression of a block var decl.
1698void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1699 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001700 assert(VD->hasAttr<BlocksAttr>() &&
1701 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001702 BlockVarCopyInits[VD] = Init;
1703}
1704
John McCalla93c9342009-12-07 02:54:59 +00001705TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001706 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001707 if (!DataSize)
1708 DataSize = TypeLoc::getFullDataSizeForType(T);
1709 else
1710 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001711 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001712
John McCalla93c9342009-12-07 02:54:59 +00001713 TypeSourceInfo *TInfo =
1714 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1715 new (TInfo) TypeSourceInfo(T);
1716 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001717}
1718
John McCalla93c9342009-12-07 02:54:59 +00001719TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001720 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001721 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001722 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001723 return DI;
1724}
1725
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001726const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001727ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001728 return getObjCLayout(D, 0);
1729}
1730
1731const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001732ASTContext::getASTObjCImplementationLayout(
1733 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001734 return getObjCLayout(D->getClassInterface(), D);
1735}
1736
Chris Lattnera7674d82007-07-13 22:13:22 +00001737//===----------------------------------------------------------------------===//
1738// Type creation/memoization methods
1739//===----------------------------------------------------------------------===//
1740
Jay Foad4ba2a172011-01-12 09:06:06 +00001741QualType
John McCall3b657512011-01-19 10:06:00 +00001742ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1743 unsigned fastQuals = quals.getFastQualifiers();
1744 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001745
1746 // Check if we've already instantiated this type.
1747 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001748 ExtQuals::Profile(ID, baseType, quals);
1749 void *insertPos = 0;
1750 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1751 assert(eq->getQualifiers() == quals);
1752 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001753 }
1754
John McCall3b657512011-01-19 10:06:00 +00001755 // If the base type is not canonical, make the appropriate canonical type.
1756 QualType canon;
1757 if (!baseType->isCanonicalUnqualified()) {
1758 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001759 canonSplit.Quals.addConsistentQualifiers(quals);
1760 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001761
1762 // Re-find the insert position.
1763 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1764 }
1765
1766 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1767 ExtQualNodes.InsertNode(eq, insertPos);
1768 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001769}
1770
Jay Foad4ba2a172011-01-12 09:06:06 +00001771QualType
1772ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001773 QualType CanT = getCanonicalType(T);
1774 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001775 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001776
John McCall0953e762009-09-24 19:53:00 +00001777 // If we are composing extended qualifiers together, merge together
1778 // into one ExtQuals node.
1779 QualifierCollector Quals;
1780 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001781
John McCall0953e762009-09-24 19:53:00 +00001782 // If this type already has an address space specified, it cannot get
1783 // another one.
1784 assert(!Quals.hasAddressSpace() &&
1785 "Type cannot be in multiple addr spaces!");
1786 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001787
John McCall0953e762009-09-24 19:53:00 +00001788 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001789}
1790
Chris Lattnerb7d25532009-02-18 22:53:11 +00001791QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001792 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001793 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001794 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001795 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001796
John McCall7f040a92010-12-24 02:08:15 +00001797 if (const PointerType *ptr = T->getAs<PointerType>()) {
1798 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001799 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001800 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1801 return getPointerType(ResultType);
1802 }
1803 }
Mike Stump1eb44332009-09-09 15:08:12 +00001804
John McCall0953e762009-09-24 19:53:00 +00001805 // If we are composing extended qualifiers together, merge together
1806 // into one ExtQuals node.
1807 QualifierCollector Quals;
1808 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001809
John McCall0953e762009-09-24 19:53:00 +00001810 // If this type already has an ObjCGC specified, it cannot get
1811 // another one.
1812 assert(!Quals.hasObjCGCAttr() &&
1813 "Type cannot have multiple ObjCGCs!");
1814 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001815
John McCall0953e762009-09-24 19:53:00 +00001816 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001817}
Chris Lattnera7674d82007-07-13 22:13:22 +00001818
John McCalle6a365d2010-12-19 02:44:49 +00001819const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1820 FunctionType::ExtInfo Info) {
1821 if (T->getExtInfo() == Info)
1822 return T;
1823
1824 QualType Result;
1825 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1826 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1827 } else {
1828 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1829 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1830 EPI.ExtInfo = Info;
1831 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1832 FPT->getNumArgs(), EPI);
1833 }
1834
1835 return cast<FunctionType>(Result.getTypePtr());
1836}
1837
Reid Spencer5f016e22007-07-11 17:01:13 +00001838/// getComplexType - Return the uniqued reference to the type for a complex
1839/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001840QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 // Unique pointers, to guarantee there is only one pointer of a particular
1842 // structure.
1843 llvm::FoldingSetNodeID ID;
1844 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 void *InsertPos = 0;
1847 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1848 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 // If the pointee type isn't canonical, this won't be a canonical type either,
1851 // so fill in the canonical type field.
1852 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001853 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001854 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 // Get the new insert position for the node we care about.
1857 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001858 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 }
John McCall6b304a02009-09-24 23:30:46 +00001860 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 Types.push_back(New);
1862 ComplexTypes.InsertNode(New, InsertPos);
1863 return QualType(New, 0);
1864}
1865
Reid Spencer5f016e22007-07-11 17:01:13 +00001866/// getPointerType - Return the uniqued reference to the type for a pointer to
1867/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001868QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 // Unique pointers, to guarantee there is only one pointer of a particular
1870 // structure.
1871 llvm::FoldingSetNodeID ID;
1872 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 void *InsertPos = 0;
1875 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1876 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 // If the pointee type isn't canonical, this won't be a canonical type either,
1879 // so fill in the canonical type field.
1880 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001881 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001882 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 // Get the new insert position for the node we care about.
1885 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001886 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 }
John McCall6b304a02009-09-24 23:30:46 +00001888 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 Types.push_back(New);
1890 PointerTypes.InsertNode(New, InsertPos);
1891 return QualType(New, 0);
1892}
1893
Mike Stump1eb44332009-09-09 15:08:12 +00001894/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001895/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001896QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001897 assert(T->isFunctionType() && "block of function types only");
1898 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001899 // structure.
1900 llvm::FoldingSetNodeID ID;
1901 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Steve Naroff5618bd42008-08-27 16:04:49 +00001903 void *InsertPos = 0;
1904 if (BlockPointerType *PT =
1905 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1906 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001907
1908 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001909 // type either so fill in the canonical type field.
1910 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001911 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001912 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Steve Naroff5618bd42008-08-27 16:04:49 +00001914 // Get the new insert position for the node we care about.
1915 BlockPointerType *NewIP =
1916 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001917 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001918 }
John McCall6b304a02009-09-24 23:30:46 +00001919 BlockPointerType *New
1920 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001921 Types.push_back(New);
1922 BlockPointerTypes.InsertNode(New, InsertPos);
1923 return QualType(New, 0);
1924}
1925
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001926/// getLValueReferenceType - Return the uniqued reference to the type for an
1927/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001928QualType
1929ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001930 assert(getCanonicalType(T) != OverloadTy &&
1931 "Unresolved overloaded function type");
1932
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 // Unique pointers, to guarantee there is only one pointer of a particular
1934 // structure.
1935 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001936 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001937
1938 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001939 if (LValueReferenceType *RT =
1940 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001942
John McCall54e14c42009-10-22 22:37:11 +00001943 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1944
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 // If the referencee type isn't canonical, this won't be a canonical type
1946 // either, so fill in the canonical type field.
1947 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001948 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1949 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1950 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001951
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001953 LValueReferenceType *NewIP =
1954 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001955 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 }
1957
John McCall6b304a02009-09-24 23:30:46 +00001958 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001959 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1960 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001962 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001963
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001964 return QualType(New, 0);
1965}
1966
1967/// getRValueReferenceType - Return the uniqued reference to the type for an
1968/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001969QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001970 // Unique pointers, to guarantee there is only one pointer of a particular
1971 // structure.
1972 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001973 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001974
1975 void *InsertPos = 0;
1976 if (RValueReferenceType *RT =
1977 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1978 return QualType(RT, 0);
1979
John McCall54e14c42009-10-22 22:37:11 +00001980 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1981
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001982 // If the referencee type isn't canonical, this won't be a canonical type
1983 // either, so fill in the canonical type field.
1984 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001985 if (InnerRef || !T.isCanonical()) {
1986 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1987 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001988
1989 // Get the new insert position for the node we care about.
1990 RValueReferenceType *NewIP =
1991 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001992 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001993 }
1994
John McCall6b304a02009-09-24 23:30:46 +00001995 RValueReferenceType *New
1996 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001997 Types.push_back(New);
1998 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 return QualType(New, 0);
2000}
2001
Sebastian Redlf30208a2009-01-24 21:16:55 +00002002/// getMemberPointerType - Return the uniqued reference to the type for a
2003/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002004QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002005 // Unique pointers, to guarantee there is only one pointer of a particular
2006 // structure.
2007 llvm::FoldingSetNodeID ID;
2008 MemberPointerType::Profile(ID, T, Cls);
2009
2010 void *InsertPos = 0;
2011 if (MemberPointerType *PT =
2012 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2013 return QualType(PT, 0);
2014
2015 // If the pointee or class type isn't canonical, this won't be a canonical
2016 // type either, so fill in the canonical type field.
2017 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002018 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002019 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2020
2021 // Get the new insert position for the node we care about.
2022 MemberPointerType *NewIP =
2023 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002024 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002025 }
John McCall6b304a02009-09-24 23:30:46 +00002026 MemberPointerType *New
2027 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002028 Types.push_back(New);
2029 MemberPointerTypes.InsertNode(New, InsertPos);
2030 return QualType(New, 0);
2031}
2032
Mike Stump1eb44332009-09-09 15:08:12 +00002033/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002034/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002035QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002036 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002037 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002038 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002039 assert((EltTy->isDependentType() ||
2040 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002041 "Constant array of VLAs is illegal!");
2042
Chris Lattner38aeec72009-05-13 04:12:56 +00002043 // Convert the array size into a canonical width matching the pointer size for
2044 // the target.
2045 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002046 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002047 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002050 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002053 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002054 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
John McCall3b657512011-01-19 10:06:00 +00002057 // If the element type isn't canonical or has qualifiers, this won't
2058 // be a canonical type either, so fill in the canonical type field.
2059 QualType Canon;
2060 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2061 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002062 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002063 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002064 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002065
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002067 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002068 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002069 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002070 }
Mike Stump1eb44332009-09-09 15:08:12 +00002071
John McCall6b304a02009-09-24 23:30:46 +00002072 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002073 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002074 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 Types.push_back(New);
2076 return QualType(New, 0);
2077}
2078
John McCallce889032011-01-18 08:40:38 +00002079/// getVariableArrayDecayedType - Turns the given type, which may be
2080/// variably-modified, into the corresponding type with all the known
2081/// sizes replaced with [*].
2082QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2083 // Vastly most common case.
2084 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002085
John McCallce889032011-01-18 08:40:38 +00002086 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002087
John McCallce889032011-01-18 08:40:38 +00002088 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002089 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002090 switch (ty->getTypeClass()) {
2091#define TYPE(Class, Base)
2092#define ABSTRACT_TYPE(Class, Base)
2093#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2094#include "clang/AST/TypeNodes.def"
2095 llvm_unreachable("didn't desugar past all non-canonical types?");
2096
2097 // These types should never be variably-modified.
2098 case Type::Builtin:
2099 case Type::Complex:
2100 case Type::Vector:
2101 case Type::ExtVector:
2102 case Type::DependentSizedExtVector:
2103 case Type::ObjCObject:
2104 case Type::ObjCInterface:
2105 case Type::ObjCObjectPointer:
2106 case Type::Record:
2107 case Type::Enum:
2108 case Type::UnresolvedUsing:
2109 case Type::TypeOfExpr:
2110 case Type::TypeOf:
2111 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002112 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002113 case Type::DependentName:
2114 case Type::InjectedClassName:
2115 case Type::TemplateSpecialization:
2116 case Type::DependentTemplateSpecialization:
2117 case Type::TemplateTypeParm:
2118 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002119 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002120 case Type::PackExpansion:
2121 llvm_unreachable("type should never be variably-modified");
2122
2123 // These types can be variably-modified but should never need to
2124 // further decay.
2125 case Type::FunctionNoProto:
2126 case Type::FunctionProto:
2127 case Type::BlockPointer:
2128 case Type::MemberPointer:
2129 return type;
2130
2131 // These types can be variably-modified. All these modifications
2132 // preserve structure except as noted by comments.
2133 // TODO: if we ever care about optimizing VLAs, there are no-op
2134 // optimizations available here.
2135 case Type::Pointer:
2136 result = getPointerType(getVariableArrayDecayedType(
2137 cast<PointerType>(ty)->getPointeeType()));
2138 break;
2139
2140 case Type::LValueReference: {
2141 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2142 result = getLValueReferenceType(
2143 getVariableArrayDecayedType(lv->getPointeeType()),
2144 lv->isSpelledAsLValue());
2145 break;
2146 }
2147
2148 case Type::RValueReference: {
2149 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2150 result = getRValueReferenceType(
2151 getVariableArrayDecayedType(lv->getPointeeType()));
2152 break;
2153 }
2154
Eli Friedmanb001de72011-10-06 23:00:33 +00002155 case Type::Atomic: {
2156 const AtomicType *at = cast<AtomicType>(ty);
2157 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2158 break;
2159 }
2160
John McCallce889032011-01-18 08:40:38 +00002161 case Type::ConstantArray: {
2162 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2163 result = getConstantArrayType(
2164 getVariableArrayDecayedType(cat->getElementType()),
2165 cat->getSize(),
2166 cat->getSizeModifier(),
2167 cat->getIndexTypeCVRQualifiers());
2168 break;
2169 }
2170
2171 case Type::DependentSizedArray: {
2172 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2173 result = getDependentSizedArrayType(
2174 getVariableArrayDecayedType(dat->getElementType()),
2175 dat->getSizeExpr(),
2176 dat->getSizeModifier(),
2177 dat->getIndexTypeCVRQualifiers(),
2178 dat->getBracketsRange());
2179 break;
2180 }
2181
2182 // Turn incomplete types into [*] types.
2183 case Type::IncompleteArray: {
2184 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2185 result = getVariableArrayType(
2186 getVariableArrayDecayedType(iat->getElementType()),
2187 /*size*/ 0,
2188 ArrayType::Normal,
2189 iat->getIndexTypeCVRQualifiers(),
2190 SourceRange());
2191 break;
2192 }
2193
2194 // Turn VLA types into [*] types.
2195 case Type::VariableArray: {
2196 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2197 result = getVariableArrayType(
2198 getVariableArrayDecayedType(vat->getElementType()),
2199 /*size*/ 0,
2200 ArrayType::Star,
2201 vat->getIndexTypeCVRQualifiers(),
2202 vat->getBracketsRange());
2203 break;
2204 }
2205 }
2206
2207 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002208 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002209}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002210
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002211/// getVariableArrayType - Returns a non-unique reference to the type for a
2212/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002213QualType ASTContext::getVariableArrayType(QualType EltTy,
2214 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002215 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002216 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002217 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002218 // Since we don't unique expressions, it isn't possible to unique VLA's
2219 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002220 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002221
John McCall3b657512011-01-19 10:06:00 +00002222 // Be sure to pull qualifiers off the element type.
2223 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2224 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002225 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002226 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002227 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002228 }
2229
John McCall6b304a02009-09-24 23:30:46 +00002230 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002231 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002232
2233 VariableArrayTypes.push_back(New);
2234 Types.push_back(New);
2235 return QualType(New, 0);
2236}
2237
Douglas Gregor898574e2008-12-05 23:32:09 +00002238/// getDependentSizedArrayType - Returns a non-unique reference to
2239/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002240/// type.
John McCall3b657512011-01-19 10:06:00 +00002241QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2242 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002243 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002244 unsigned elementTypeQuals,
2245 SourceRange brackets) const {
2246 assert((!numElements || numElements->isTypeDependent() ||
2247 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002248 "Size must be type- or value-dependent!");
2249
John McCall3b657512011-01-19 10:06:00 +00002250 // Dependently-sized array types that do not have a specified number
2251 // of elements will have their sizes deduced from a dependent
2252 // initializer. We do no canonicalization here at all, which is okay
2253 // because they can't be used in most locations.
2254 if (!numElements) {
2255 DependentSizedArrayType *newType
2256 = new (*this, TypeAlignment)
2257 DependentSizedArrayType(*this, elementType, QualType(),
2258 numElements, ASM, elementTypeQuals,
2259 brackets);
2260 Types.push_back(newType);
2261 return QualType(newType, 0);
2262 }
2263
2264 // Otherwise, we actually build a new type every time, but we
2265 // also build a canonical type.
2266
2267 SplitQualType canonElementType = getCanonicalType(elementType).split();
2268
2269 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002270 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002271 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002272 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002273 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002274
John McCall3b657512011-01-19 10:06:00 +00002275 // Look for an existing type with these properties.
2276 DependentSizedArrayType *canonTy =
2277 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002278
John McCall3b657512011-01-19 10:06:00 +00002279 // If we don't have one, build one.
2280 if (!canonTy) {
2281 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002282 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002283 QualType(), numElements, ASM, elementTypeQuals,
2284 brackets);
2285 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2286 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002287 }
2288
John McCall3b657512011-01-19 10:06:00 +00002289 // Apply qualifiers from the element type to the array.
2290 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002291 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002292
John McCall3b657512011-01-19 10:06:00 +00002293 // If we didn't need extra canonicalization for the element type,
2294 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002295 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002296 return canon;
2297
2298 // Otherwise, we need to build a type which follows the spelling
2299 // of the element type.
2300 DependentSizedArrayType *sugaredType
2301 = new (*this, TypeAlignment)
2302 DependentSizedArrayType(*this, elementType, canon, numElements,
2303 ASM, elementTypeQuals, brackets);
2304 Types.push_back(sugaredType);
2305 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002306}
2307
John McCall3b657512011-01-19 10:06:00 +00002308QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002309 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002310 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002311 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002312 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002313
John McCall3b657512011-01-19 10:06:00 +00002314 void *insertPos = 0;
2315 if (IncompleteArrayType *iat =
2316 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2317 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002318
2319 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002320 // either, so fill in the canonical type field. We also have to pull
2321 // qualifiers off the element type.
2322 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002323
John McCall3b657512011-01-19 10:06:00 +00002324 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2325 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002326 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002327 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002328 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002329
2330 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002331 IncompleteArrayType *existing =
2332 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2333 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002334 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002335
John McCall3b657512011-01-19 10:06:00 +00002336 IncompleteArrayType *newType = new (*this, TypeAlignment)
2337 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002338
John McCall3b657512011-01-19 10:06:00 +00002339 IncompleteArrayTypes.InsertNode(newType, insertPos);
2340 Types.push_back(newType);
2341 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002342}
2343
Steve Naroff73322922007-07-18 18:00:27 +00002344/// getVectorType - Return the unique reference to a vector type of
2345/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002346QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002347 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002348 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Reid Spencer5f016e22007-07-11 17:01:13 +00002350 // Check if we've already instantiated a vector of this type.
2351 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002352 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002353
Reid Spencer5f016e22007-07-11 17:01:13 +00002354 void *InsertPos = 0;
2355 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2356 return QualType(VTP, 0);
2357
2358 // If the element type isn't canonical, this won't be a canonical type either,
2359 // so fill in the canonical type field.
2360 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002361 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002362 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 // Get the new insert position for the node we care about.
2365 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002366 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 }
John McCall6b304a02009-09-24 23:30:46 +00002368 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002369 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 VectorTypes.InsertNode(New, InsertPos);
2371 Types.push_back(New);
2372 return QualType(New, 0);
2373}
2374
Nate Begeman213541a2008-04-18 23:10:10 +00002375/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002376/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002377QualType
2378ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002379 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Steve Naroff73322922007-07-18 18:00:27 +00002381 // Check if we've already instantiated a vector of this type.
2382 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002383 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002384 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002385 void *InsertPos = 0;
2386 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2387 return QualType(VTP, 0);
2388
2389 // If the element type isn't canonical, this won't be a canonical type either,
2390 // so fill in the canonical type field.
2391 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002392 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002393 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Steve Naroff73322922007-07-18 18:00:27 +00002395 // Get the new insert position for the node we care about.
2396 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002397 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002398 }
John McCall6b304a02009-09-24 23:30:46 +00002399 ExtVectorType *New = new (*this, TypeAlignment)
2400 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002401 VectorTypes.InsertNode(New, InsertPos);
2402 Types.push_back(New);
2403 return QualType(New, 0);
2404}
2405
Jay Foad4ba2a172011-01-12 09:06:06 +00002406QualType
2407ASTContext::getDependentSizedExtVectorType(QualType vecType,
2408 Expr *SizeExpr,
2409 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002410 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002411 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002412 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002414 void *InsertPos = 0;
2415 DependentSizedExtVectorType *Canon
2416 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2417 DependentSizedExtVectorType *New;
2418 if (Canon) {
2419 // We already have a canonical version of this array type; use it as
2420 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002421 New = new (*this, TypeAlignment)
2422 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2423 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002424 } else {
2425 QualType CanonVecTy = getCanonicalType(vecType);
2426 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002427 New = new (*this, TypeAlignment)
2428 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2429 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002430
2431 DependentSizedExtVectorType *CanonCheck
2432 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2433 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2434 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002435 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2436 } else {
2437 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2438 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002439 New = new (*this, TypeAlignment)
2440 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002441 }
2442 }
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002444 Types.push_back(New);
2445 return QualType(New, 0);
2446}
2447
Douglas Gregor72564e72009-02-26 23:50:07 +00002448/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002449///
Jay Foad4ba2a172011-01-12 09:06:06 +00002450QualType
2451ASTContext::getFunctionNoProtoType(QualType ResultTy,
2452 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002453 const CallingConv DefaultCC = Info.getCC();
2454 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2455 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002456 // Unique functions, to guarantee there is only one function of a particular
2457 // structure.
2458 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002459 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002460
Reid Spencer5f016e22007-07-11 17:01:13 +00002461 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002462 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002463 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Reid Spencer5f016e22007-07-11 17:01:13 +00002466 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002467 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002468 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002469 Canonical =
2470 getFunctionNoProtoType(getCanonicalType(ResultTy),
2471 Info.withCallingConv(getCanonicalCallConv(CallConv)));
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.
Douglas Gregor72564e72009-02-26 23:50:07 +00002474 FunctionNoProtoType *NewIP =
2475 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002476 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002477 }
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Roman Divackycfe9af22011-03-01 17:40:53 +00002479 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002480 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002481 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002483 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 return QualType(New, 0);
2485}
2486
2487/// getFunctionType - Return a normal function type with a typed argument
2488/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002489QualType
2490ASTContext::getFunctionType(QualType ResultTy,
2491 const QualType *ArgArray, unsigned NumArgs,
2492 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002493 // Unique functions, to guarantee there is only one function of a particular
2494 // structure.
2495 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002496 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002497
2498 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002499 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002500 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002501 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002502
2503 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002504 bool isCanonical =
2505 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2506 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002507 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002508 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002509 isCanonical = false;
2510
Roman Divackycfe9af22011-03-01 17:40:53 +00002511 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2512 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2513 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002514
Reid Spencer5f016e22007-07-11 17:01:13 +00002515 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002516 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002518 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002519 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 CanonicalArgs.reserve(NumArgs);
2521 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002522 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002523
John McCalle23cf432010-12-14 08:05:40 +00002524 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002525 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002526 CanonicalEPI.ExceptionSpecType = EST_None;
2527 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002528 CanonicalEPI.ExtInfo
2529 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2530
Chris Lattnerf52ab252008-04-06 22:59:24 +00002531 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002532 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002533 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002534
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002536 FunctionProtoType *NewIP =
2537 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002538 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002539 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002540
John McCallf85e1932011-06-15 23:02:42 +00002541 // FunctionProtoType objects are allocated with extra bytes after
2542 // them for three variable size arrays at the end:
2543 // - parameter types
2544 // - exception types
2545 // - consumed-arguments flags
2546 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002547 // expression, or information used to resolve the exception
2548 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002549 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002550 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002551 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002552 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002553 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002554 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002555 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002556 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002557 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2558 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002559 }
John McCallf85e1932011-06-15 23:02:42 +00002560 if (EPI.ConsumedArguments)
2561 Size += NumArgs * sizeof(bool);
2562
John McCalle23cf432010-12-14 08:05:40 +00002563 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002564 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2565 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002566 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002567 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002568 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 return QualType(FTP, 0);
2570}
2571
John McCall3cb0ebd2010-03-10 03:28:59 +00002572#ifndef NDEBUG
2573static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2574 if (!isa<CXXRecordDecl>(D)) return false;
2575 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2576 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2577 return true;
2578 if (RD->getDescribedClassTemplate() &&
2579 !isa<ClassTemplateSpecializationDecl>(RD))
2580 return true;
2581 return false;
2582}
2583#endif
2584
2585/// getInjectedClassNameType - Return the unique reference to the
2586/// injected class name type for the specified templated declaration.
2587QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002588 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002589 assert(NeedsInjectedClassNameType(Decl));
2590 if (Decl->TypeForDecl) {
2591 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002592 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002593 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2594 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2595 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2596 } else {
John McCallf4c73712011-01-19 06:33:43 +00002597 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002598 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002599 Decl->TypeForDecl = newType;
2600 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002601 }
2602 return QualType(Decl->TypeForDecl, 0);
2603}
2604
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002605/// getTypeDeclType - Return the unique reference to the type for the
2606/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002607QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002608 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002609 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Richard Smith162e1c12011-04-15 14:24:37 +00002611 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002612 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002613
John McCallbecb8d52010-03-10 06:48:02 +00002614 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2615 "Template type parameter types are always available.");
2616
John McCall19c85762010-02-16 03:57:14 +00002617 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002618 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002619 "struct/union has previous declaration");
2620 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002621 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002622 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002623 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002624 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002625 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002626 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002627 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002628 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2629 Decl->TypeForDecl = newType;
2630 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002631 } else
John McCallbecb8d52010-03-10 06:48:02 +00002632 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002633
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002634 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002635}
2636
Reid Spencer5f016e22007-07-11 17:01:13 +00002637/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002638/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002639QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002640ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2641 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002644 if (Canonical.isNull())
2645 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002646 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002647 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002648 Decl->TypeForDecl = newType;
2649 Types.push_back(newType);
2650 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002651}
2652
Jay Foad4ba2a172011-01-12 09:06:06 +00002653QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002654 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2655
Douglas Gregoref96ee02012-01-14 16:38:05 +00002656 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002657 if (PrevDecl->TypeForDecl)
2658 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2659
John McCallf4c73712011-01-19 06:33:43 +00002660 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2661 Decl->TypeForDecl = newType;
2662 Types.push_back(newType);
2663 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002664}
2665
Jay Foad4ba2a172011-01-12 09:06:06 +00002666QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002667 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2668
Douglas Gregoref96ee02012-01-14 16:38:05 +00002669 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002670 if (PrevDecl->TypeForDecl)
2671 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2672
John McCallf4c73712011-01-19 06:33:43 +00002673 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2674 Decl->TypeForDecl = newType;
2675 Types.push_back(newType);
2676 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002677}
2678
John McCall9d156a72011-01-06 01:58:22 +00002679QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2680 QualType modifiedType,
2681 QualType equivalentType) {
2682 llvm::FoldingSetNodeID id;
2683 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2684
2685 void *insertPos = 0;
2686 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2687 if (type) return QualType(type, 0);
2688
2689 QualType canon = getCanonicalType(equivalentType);
2690 type = new (*this, TypeAlignment)
2691 AttributedType(canon, attrKind, modifiedType, equivalentType);
2692
2693 Types.push_back(type);
2694 AttributedTypes.InsertNode(type, insertPos);
2695
2696 return QualType(type, 0);
2697}
2698
2699
John McCall49a832b2009-10-18 09:09:24 +00002700/// \brief Retrieve a substitution-result type.
2701QualType
2702ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002703 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002704 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002705 && "replacement types must always be canonical");
2706
2707 llvm::FoldingSetNodeID ID;
2708 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2709 void *InsertPos = 0;
2710 SubstTemplateTypeParmType *SubstParm
2711 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2712
2713 if (!SubstParm) {
2714 SubstParm = new (*this, TypeAlignment)
2715 SubstTemplateTypeParmType(Parm, Replacement);
2716 Types.push_back(SubstParm);
2717 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2718 }
2719
2720 return QualType(SubstParm, 0);
2721}
2722
Douglas Gregorc3069d62011-01-14 02:55:32 +00002723/// \brief Retrieve a
2724QualType ASTContext::getSubstTemplateTypeParmPackType(
2725 const TemplateTypeParmType *Parm,
2726 const TemplateArgument &ArgPack) {
2727#ifndef NDEBUG
2728 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2729 PEnd = ArgPack.pack_end();
2730 P != PEnd; ++P) {
2731 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2732 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2733 }
2734#endif
2735
2736 llvm::FoldingSetNodeID ID;
2737 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2738 void *InsertPos = 0;
2739 if (SubstTemplateTypeParmPackType *SubstParm
2740 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2741 return QualType(SubstParm, 0);
2742
2743 QualType Canon;
2744 if (!Parm->isCanonicalUnqualified()) {
2745 Canon = getCanonicalType(QualType(Parm, 0));
2746 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2747 ArgPack);
2748 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2749 }
2750
2751 SubstTemplateTypeParmPackType *SubstParm
2752 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2753 ArgPack);
2754 Types.push_back(SubstParm);
2755 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2756 return QualType(SubstParm, 0);
2757}
2758
Douglas Gregorfab9d672009-02-05 23:33:38 +00002759/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002760/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002761/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002762QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002763 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002764 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002765 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002766 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002767 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002768 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002769 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2770
2771 if (TypeParm)
2772 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002774 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002775 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002776 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002777
2778 TemplateTypeParmType *TypeCheck
2779 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2780 assert(!TypeCheck && "Template type parameter canonical type broken");
2781 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002782 } else
John McCall6b304a02009-09-24 23:30:46 +00002783 TypeParm = new (*this, TypeAlignment)
2784 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002785
2786 Types.push_back(TypeParm);
2787 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2788
2789 return QualType(TypeParm, 0);
2790}
2791
John McCall3cb0ebd2010-03-10 03:28:59 +00002792TypeSourceInfo *
2793ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2794 SourceLocation NameLoc,
2795 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002796 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002797 assert(!Name.getAsDependentTemplateName() &&
2798 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002799 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002800
2801 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2802 TemplateSpecializationTypeLoc TL
2803 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002804 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002805 TL.setTemplateNameLoc(NameLoc);
2806 TL.setLAngleLoc(Args.getLAngleLoc());
2807 TL.setRAngleLoc(Args.getRAngleLoc());
2808 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2809 TL.setArgLocInfo(i, Args[i].getLocInfo());
2810 return DI;
2811}
2812
Mike Stump1eb44332009-09-09 15:08:12 +00002813QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002814ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002815 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002816 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002817 assert(!Template.getAsDependentTemplateName() &&
2818 "No dependent template names here!");
2819
John McCalld5532b62009-11-23 01:53:49 +00002820 unsigned NumArgs = Args.size();
2821
Chris Lattner5f9e2722011-07-23 10:55:15 +00002822 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002823 ArgVec.reserve(NumArgs);
2824 for (unsigned i = 0; i != NumArgs; ++i)
2825 ArgVec.push_back(Args[i].getArgument());
2826
John McCall31f17ec2010-04-27 00:57:59 +00002827 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002828 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002829}
2830
Douglas Gregorb70126a2012-02-03 17:16:23 +00002831#ifndef NDEBUG
2832static bool hasAnyPackExpansions(const TemplateArgument *Args,
2833 unsigned NumArgs) {
2834 for (unsigned I = 0; I != NumArgs; ++I)
2835 if (Args[I].isPackExpansion())
2836 return true;
2837
2838 return true;
2839}
2840#endif
2841
John McCall833ca992009-10-29 08:12:44 +00002842QualType
2843ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002844 const TemplateArgument *Args,
2845 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002846 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002847 assert(!Template.getAsDependentTemplateName() &&
2848 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002849 // Look through qualified template names.
2850 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2851 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002852
Douglas Gregorb70126a2012-02-03 17:16:23 +00002853 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002854 Template.getAsTemplateDecl() &&
2855 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002856 QualType CanonType;
2857 if (!Underlying.isNull())
2858 CanonType = getCanonicalType(Underlying);
2859 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002860 // We can get here with an alias template when the specialization contains
2861 // a pack expansion that does not match up with a parameter pack.
2862 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2863 "Caller must compute aliased type");
2864 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002865 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2866 NumArgs);
2867 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002868
Douglas Gregor1275ae02009-07-28 23:00:59 +00002869 // Allocate the (non-canonical) template specialization type, but don't
2870 // try to unique it: these types typically have location information that
2871 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002872 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2873 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002874 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002875 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002876 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002877 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2878 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002879
Douglas Gregor55f6b142009-02-09 18:46:07 +00002880 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002881 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002882}
2883
Mike Stump1eb44332009-09-09 15:08:12 +00002884QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002885ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2886 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002887 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002888 assert(!Template.getAsDependentTemplateName() &&
2889 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002890
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002891 // Look through qualified template names.
2892 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2893 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002894
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002895 // Build the canonical template specialization type.
2896 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002897 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002898 CanonArgs.reserve(NumArgs);
2899 for (unsigned I = 0; I != NumArgs; ++I)
2900 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2901
2902 // Determine whether this canonical template specialization type already
2903 // exists.
2904 llvm::FoldingSetNodeID ID;
2905 TemplateSpecializationType::Profile(ID, CanonTemplate,
2906 CanonArgs.data(), NumArgs, *this);
2907
2908 void *InsertPos = 0;
2909 TemplateSpecializationType *Spec
2910 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2911
2912 if (!Spec) {
2913 // Allocate a new canonical template specialization type.
2914 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2915 sizeof(TemplateArgument) * NumArgs),
2916 TypeAlignment);
2917 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2918 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002919 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002920 Types.push_back(Spec);
2921 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2922 }
2923
2924 assert(Spec->isDependentType() &&
2925 "Non-dependent template-id type must have a canonical type");
2926 return QualType(Spec, 0);
2927}
2928
2929QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002930ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2931 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002932 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002933 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002934 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002935
2936 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002937 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002938 if (T)
2939 return QualType(T, 0);
2940
Douglas Gregor789b1f62010-02-04 18:10:26 +00002941 QualType Canon = NamedType;
2942 if (!Canon.isCanonical()) {
2943 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002944 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2945 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002946 (void)CheckT;
2947 }
2948
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002949 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002950 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002951 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002952 return QualType(T, 0);
2953}
2954
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002955QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002956ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002957 llvm::FoldingSetNodeID ID;
2958 ParenType::Profile(ID, InnerType);
2959
2960 void *InsertPos = 0;
2961 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2962 if (T)
2963 return QualType(T, 0);
2964
2965 QualType Canon = InnerType;
2966 if (!Canon.isCanonical()) {
2967 Canon = getCanonicalType(InnerType);
2968 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2969 assert(!CheckT && "Paren canonical type broken");
2970 (void)CheckT;
2971 }
2972
2973 T = new (*this) ParenType(InnerType, Canon);
2974 Types.push_back(T);
2975 ParenTypes.InsertNode(T, InsertPos);
2976 return QualType(T, 0);
2977}
2978
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002979QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2980 NestedNameSpecifier *NNS,
2981 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002982 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002983 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2984
2985 if (Canon.isNull()) {
2986 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002987 ElaboratedTypeKeyword CanonKeyword = Keyword;
2988 if (Keyword == ETK_None)
2989 CanonKeyword = ETK_Typename;
2990
2991 if (CanonNNS != NNS || CanonKeyword != Keyword)
2992 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002993 }
2994
2995 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002996 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002997
2998 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002999 DependentNameType *T
3000 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003001 if (T)
3002 return QualType(T, 0);
3003
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003004 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003005 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003006 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003007 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003008}
3009
Mike Stump1eb44332009-09-09 15:08:12 +00003010QualType
John McCall33500952010-06-11 00:33:02 +00003011ASTContext::getDependentTemplateSpecializationType(
3012 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003013 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003014 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003015 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003016 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003017 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003018 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3019 ArgCopy.push_back(Args[I].getArgument());
3020 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3021 ArgCopy.size(),
3022 ArgCopy.data());
3023}
3024
3025QualType
3026ASTContext::getDependentTemplateSpecializationType(
3027 ElaboratedTypeKeyword Keyword,
3028 NestedNameSpecifier *NNS,
3029 const IdentifierInfo *Name,
3030 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003031 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003032 assert((!NNS || NNS->isDependent()) &&
3033 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003034
Douglas Gregor789b1f62010-02-04 18:10:26 +00003035 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003036 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3037 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003038
3039 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003040 DependentTemplateSpecializationType *T
3041 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003042 if (T)
3043 return QualType(T, 0);
3044
John McCall33500952010-06-11 00:33:02 +00003045 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003046
John McCall33500952010-06-11 00:33:02 +00003047 ElaboratedTypeKeyword CanonKeyword = Keyword;
3048 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3049
3050 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003051 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003052 for (unsigned I = 0; I != NumArgs; ++I) {
3053 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3054 if (!CanonArgs[I].structurallyEquals(Args[I]))
3055 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003056 }
3057
John McCall33500952010-06-11 00:33:02 +00003058 QualType Canon;
3059 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3060 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3061 Name, NumArgs,
3062 CanonArgs.data());
3063
3064 // Find the insert position again.
3065 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3066 }
3067
3068 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3069 sizeof(TemplateArgument) * NumArgs),
3070 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003071 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003072 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003073 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003074 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003075 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003076}
3077
Douglas Gregorcded4f62011-01-14 17:04:44 +00003078QualType ASTContext::getPackExpansionType(QualType Pattern,
3079 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003080 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003081 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003082
3083 assert(Pattern->containsUnexpandedParameterPack() &&
3084 "Pack expansions must expand one or more parameter packs");
3085 void *InsertPos = 0;
3086 PackExpansionType *T
3087 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3088 if (T)
3089 return QualType(T, 0);
3090
3091 QualType Canon;
3092 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003093 Canon = getCanonicalType(Pattern);
3094 // The canonical type might not contain an unexpanded parameter pack, if it
3095 // contains an alias template specialization which ignores one of its
3096 // parameters.
3097 if (Canon->containsUnexpandedParameterPack()) {
3098 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003099
Richard Smithd8672ef2012-07-16 00:20:35 +00003100 // Find the insert position again, in case we inserted an element into
3101 // PackExpansionTypes and invalidated our insert position.
3102 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3103 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003104 }
3105
Douglas Gregorcded4f62011-01-14 17:04:44 +00003106 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003107 Types.push_back(T);
3108 PackExpansionTypes.InsertNode(T, InsertPos);
3109 return QualType(T, 0);
3110}
3111
Chris Lattner88cb27a2008-04-07 04:56:42 +00003112/// CmpProtocolNames - Comparison predicate for sorting protocols
3113/// alphabetically.
3114static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3115 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003116 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003117}
3118
John McCallc12c5bb2010-05-15 11:32:37 +00003119static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003120 unsigned NumProtocols) {
3121 if (NumProtocols == 0) return true;
3122
Douglas Gregor61cc2962012-01-02 02:00:30 +00003123 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3124 return false;
3125
John McCall54e14c42009-10-22 22:37:11 +00003126 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003127 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3128 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003129 return false;
3130 return true;
3131}
3132
3133static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003134 unsigned &NumProtocols) {
3135 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Chris Lattner88cb27a2008-04-07 04:56:42 +00003137 // Sort protocols, keyed by name.
3138 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3139
Douglas Gregor61cc2962012-01-02 02:00:30 +00003140 // Canonicalize.
3141 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3142 Protocols[I] = Protocols[I]->getCanonicalDecl();
3143
Chris Lattner88cb27a2008-04-07 04:56:42 +00003144 // Remove duplicates.
3145 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3146 NumProtocols = ProtocolsEnd-Protocols;
3147}
3148
John McCallc12c5bb2010-05-15 11:32:37 +00003149QualType ASTContext::getObjCObjectType(QualType BaseType,
3150 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003151 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003152 // If the base type is an interface and there aren't any protocols
3153 // to add, then the interface type will do just fine.
3154 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3155 return BaseType;
3156
3157 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003158 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003159 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003160 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003161 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3162 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003163
John McCallc12c5bb2010-05-15 11:32:37 +00003164 // Build the canonical type, which has the canonical base type and
3165 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003166 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003167 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3168 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3169 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003170 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003171 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003172 unsigned UniqueCount = NumProtocols;
3173
John McCall54e14c42009-10-22 22:37:11 +00003174 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003175 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3176 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003177 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003178 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3179 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003180 }
3181
3182 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003183 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3184 }
3185
3186 unsigned Size = sizeof(ObjCObjectTypeImpl);
3187 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3188 void *Mem = Allocate(Size, TypeAlignment);
3189 ObjCObjectTypeImpl *T =
3190 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3191
3192 Types.push_back(T);
3193 ObjCObjectTypes.InsertNode(T, InsertPos);
3194 return QualType(T, 0);
3195}
3196
3197/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3198/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003199QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003200 llvm::FoldingSetNodeID ID;
3201 ObjCObjectPointerType::Profile(ID, ObjectT);
3202
3203 void *InsertPos = 0;
3204 if (ObjCObjectPointerType *QT =
3205 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3206 return QualType(QT, 0);
3207
3208 // Find the canonical object type.
3209 QualType Canonical;
3210 if (!ObjectT.isCanonical()) {
3211 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3212
3213 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003214 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3215 }
3216
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003217 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003218 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3219 ObjCObjectPointerType *QType =
3220 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003221
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003222 Types.push_back(QType);
3223 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003224 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003225}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003226
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003227/// getObjCInterfaceType - Return the unique reference to the type for the
3228/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003229QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3230 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003231 if (Decl->TypeForDecl)
3232 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Douglas Gregor0af55012011-12-16 03:12:41 +00003234 if (PrevDecl) {
3235 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3236 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3237 return QualType(PrevDecl->TypeForDecl, 0);
3238 }
3239
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003240 // Prefer the definition, if there is one.
3241 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3242 Decl = Def;
3243
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003244 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3245 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3246 Decl->TypeForDecl = T;
3247 Types.push_back(T);
3248 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003249}
3250
Douglas Gregor72564e72009-02-26 23:50:07 +00003251/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3252/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003253/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003254/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003255/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003256QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003257 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003258 if (tofExpr->isTypeDependent()) {
3259 llvm::FoldingSetNodeID ID;
3260 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003261
Douglas Gregorb1975722009-07-30 23:18:24 +00003262 void *InsertPos = 0;
3263 DependentTypeOfExprType *Canon
3264 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3265 if (Canon) {
3266 // We already have a "canonical" version of an identical, dependent
3267 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003268 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003269 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003270 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003271 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003272 Canon
3273 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003274 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3275 toe = Canon;
3276 }
3277 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003278 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003279 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003280 }
Steve Naroff9752f252007-08-01 18:02:17 +00003281 Types.push_back(toe);
3282 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003283}
3284
Steve Naroff9752f252007-08-01 18:02:17 +00003285/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3286/// TypeOfType AST's. The only motivation to unique these nodes would be
3287/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003288/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003289/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003290QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003291 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003292 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003293 Types.push_back(tot);
3294 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003295}
3296
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003297
Anders Carlsson395b4752009-06-24 19:06:50 +00003298/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3299/// DecltypeType AST's. The only motivation to unique these nodes would be
3300/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003301/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003302/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003303QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003304 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003305
3306 // C++0x [temp.type]p2:
3307 // If an expression e involves a template parameter, decltype(e) denotes a
3308 // unique dependent type. Two such decltype-specifiers refer to the same
3309 // type only if their expressions are equivalent (14.5.6.1).
3310 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003311 llvm::FoldingSetNodeID ID;
3312 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003314 void *InsertPos = 0;
3315 DependentDecltypeType *Canon
3316 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3317 if (Canon) {
3318 // We already have a "canonical" version of an equivalent, dependent
3319 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003320 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003321 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003322 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003323 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003324 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003325 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3326 dt = Canon;
3327 }
3328 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003329 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3330 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003331 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003332 Types.push_back(dt);
3333 return QualType(dt, 0);
3334}
3335
Sean Huntca63c202011-05-24 22:41:36 +00003336/// getUnaryTransformationType - We don't unique these, since the memory
3337/// savings are minimal and these are rare.
3338QualType ASTContext::getUnaryTransformType(QualType BaseType,
3339 QualType UnderlyingType,
3340 UnaryTransformType::UTTKind Kind)
3341 const {
3342 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003343 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3344 Kind,
3345 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003346 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003347 Types.push_back(Ty);
3348 return QualType(Ty, 0);
3349}
3350
Richard Smith483b9f32011-02-21 20:05:19 +00003351/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003352QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003353 void *InsertPos = 0;
3354 if (!DeducedType.isNull()) {
3355 // Look in the folding set for an existing type.
3356 llvm::FoldingSetNodeID ID;
3357 AutoType::Profile(ID, DeducedType);
3358 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3359 return QualType(AT, 0);
3360 }
3361
3362 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3363 Types.push_back(AT);
3364 if (InsertPos)
3365 AutoTypes.InsertNode(AT, InsertPos);
3366 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003367}
3368
Eli Friedmanb001de72011-10-06 23:00:33 +00003369/// getAtomicType - Return the uniqued reference to the atomic type for
3370/// the given value type.
3371QualType ASTContext::getAtomicType(QualType T) const {
3372 // Unique pointers, to guarantee there is only one pointer of a particular
3373 // structure.
3374 llvm::FoldingSetNodeID ID;
3375 AtomicType::Profile(ID, T);
3376
3377 void *InsertPos = 0;
3378 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3379 return QualType(AT, 0);
3380
3381 // If the atomic value type isn't canonical, this won't be a canonical type
3382 // either, so fill in the canonical type field.
3383 QualType Canonical;
3384 if (!T.isCanonical()) {
3385 Canonical = getAtomicType(getCanonicalType(T));
3386
3387 // Get the new insert position for the node we care about.
3388 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3389 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3390 }
3391 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3392 Types.push_back(New);
3393 AtomicTypes.InsertNode(New, InsertPos);
3394 return QualType(New, 0);
3395}
3396
Richard Smithad762fc2011-04-14 22:09:26 +00003397/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3398QualType ASTContext::getAutoDeductType() const {
3399 if (AutoDeductTy.isNull())
3400 AutoDeductTy = getAutoType(QualType());
3401 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3402 return AutoDeductTy;
3403}
3404
3405/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3406QualType ASTContext::getAutoRRefDeductType() const {
3407 if (AutoRRefDeductTy.isNull())
3408 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3409 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3410 return AutoRRefDeductTy;
3411}
3412
Reid Spencer5f016e22007-07-11 17:01:13 +00003413/// getTagDeclType - Return the unique reference to the type for the
3414/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003415QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003416 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003417 // FIXME: What is the design on getTagDeclType when it requires casting
3418 // away const? mutable?
3419 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003420}
3421
Mike Stump1eb44332009-09-09 15:08:12 +00003422/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3423/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3424/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003425CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003426 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003427}
3428
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003429/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3430CanQualType ASTContext::getIntMaxType() const {
3431 return getFromTargetType(Target->getIntMaxType());
3432}
3433
3434/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3435CanQualType ASTContext::getUIntMaxType() const {
3436 return getFromTargetType(Target->getUIntMaxType());
3437}
3438
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003439/// getSignedWCharType - Return the type of "signed wchar_t".
3440/// Used when in C++, as a GCC extension.
3441QualType ASTContext::getSignedWCharType() const {
3442 // FIXME: derive from "Target" ?
3443 return WCharTy;
3444}
3445
3446/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3447/// Used when in C++, as a GCC extension.
3448QualType ASTContext::getUnsignedWCharType() const {
3449 // FIXME: derive from "Target" ?
3450 return UnsignedIntTy;
3451}
3452
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003453/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003454/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3455QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003456 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003457}
3458
Chris Lattnere6327742008-04-02 05:18:44 +00003459//===----------------------------------------------------------------------===//
3460// Type Operators
3461//===----------------------------------------------------------------------===//
3462
Jay Foad4ba2a172011-01-12 09:06:06 +00003463CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003464 // Push qualifiers into arrays, and then discard any remaining
3465 // qualifiers.
3466 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003467 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003468 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003469 QualType Result;
3470 if (isa<ArrayType>(Ty)) {
3471 Result = getArrayDecayedType(QualType(Ty,0));
3472 } else if (isa<FunctionType>(Ty)) {
3473 Result = getPointerType(QualType(Ty, 0));
3474 } else {
3475 Result = QualType(Ty, 0);
3476 }
3477
3478 return CanQualType::CreateUnsafe(Result);
3479}
3480
John McCall62c28c82011-01-18 07:41:22 +00003481QualType ASTContext::getUnqualifiedArrayType(QualType type,
3482 Qualifiers &quals) {
3483 SplitQualType splitType = type.getSplitUnqualifiedType();
3484
3485 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3486 // the unqualified desugared type and then drops it on the floor.
3487 // We then have to strip that sugar back off with
3488 // getUnqualifiedDesugaredType(), which is silly.
3489 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003490 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003491
3492 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003493 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003494 quals = splitType.Quals;
3495 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003496 }
3497
John McCall62c28c82011-01-18 07:41:22 +00003498 // Otherwise, recurse on the array's element type.
3499 QualType elementType = AT->getElementType();
3500 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3501
3502 // If that didn't change the element type, AT has no qualifiers, so we
3503 // can just use the results in splitType.
3504 if (elementType == unqualElementType) {
3505 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003506 quals = splitType.Quals;
3507 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003508 }
3509
3510 // Otherwise, add in the qualifiers from the outermost type, then
3511 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003512 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003513
Douglas Gregor9dadd942010-05-17 18:45:21 +00003514 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003515 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003516 CAT->getSizeModifier(), 0);
3517 }
3518
Douglas Gregor9dadd942010-05-17 18:45:21 +00003519 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003520 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003521 }
3522
Douglas Gregor9dadd942010-05-17 18:45:21 +00003523 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003524 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003525 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003526 VAT->getSizeModifier(),
3527 VAT->getIndexTypeCVRQualifiers(),
3528 VAT->getBracketsRange());
3529 }
3530
3531 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003532 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003533 DSAT->getSizeModifier(), 0,
3534 SourceRange());
3535}
3536
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003537/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3538/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3539/// they point to and return true. If T1 and T2 aren't pointer types
3540/// or pointer-to-member types, or if they are not similar at this
3541/// level, returns false and leaves T1 and T2 unchanged. Top-level
3542/// qualifiers on T1 and T2 are ignored. This function will typically
3543/// be called in a loop that successively "unwraps" pointer and
3544/// pointer-to-member types to compare them at each level.
3545bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3546 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3547 *T2PtrType = T2->getAs<PointerType>();
3548 if (T1PtrType && T2PtrType) {
3549 T1 = T1PtrType->getPointeeType();
3550 T2 = T2PtrType->getPointeeType();
3551 return true;
3552 }
3553
3554 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3555 *T2MPType = T2->getAs<MemberPointerType>();
3556 if (T1MPType && T2MPType &&
3557 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3558 QualType(T2MPType->getClass(), 0))) {
3559 T1 = T1MPType->getPointeeType();
3560 T2 = T2MPType->getPointeeType();
3561 return true;
3562 }
3563
David Blaikie4e4d0842012-03-11 07:00:24 +00003564 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003565 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3566 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3567 if (T1OPType && T2OPType) {
3568 T1 = T1OPType->getPointeeType();
3569 T2 = T2OPType->getPointeeType();
3570 return true;
3571 }
3572 }
3573
3574 // FIXME: Block pointers, too?
3575
3576 return false;
3577}
3578
Jay Foad4ba2a172011-01-12 09:06:06 +00003579DeclarationNameInfo
3580ASTContext::getNameForTemplate(TemplateName Name,
3581 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003582 switch (Name.getKind()) {
3583 case TemplateName::QualifiedTemplate:
3584 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003585 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003586 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3587 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003588
John McCall14606042011-06-30 08:33:18 +00003589 case TemplateName::OverloadedTemplate: {
3590 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3591 // DNInfo work in progress: CHECKME: what about DNLoc?
3592 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3593 }
3594
3595 case TemplateName::DependentTemplate: {
3596 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003597 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003598 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003599 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3600 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003601 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003602 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3603 // DNInfo work in progress: FIXME: source locations?
3604 DeclarationNameLoc DNLoc;
3605 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3606 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3607 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003608 }
3609 }
3610
John McCall14606042011-06-30 08:33:18 +00003611 case TemplateName::SubstTemplateTemplateParm: {
3612 SubstTemplateTemplateParmStorage *subst
3613 = Name.getAsSubstTemplateTemplateParm();
3614 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3615 NameLoc);
3616 }
3617
3618 case TemplateName::SubstTemplateTemplateParmPack: {
3619 SubstTemplateTemplateParmPackStorage *subst
3620 = Name.getAsSubstTemplateTemplateParmPack();
3621 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3622 NameLoc);
3623 }
3624 }
3625
3626 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003627}
3628
Jay Foad4ba2a172011-01-12 09:06:06 +00003629TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003630 switch (Name.getKind()) {
3631 case TemplateName::QualifiedTemplate:
3632 case TemplateName::Template: {
3633 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003634 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003635 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003636 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3637
3638 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003639 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003640 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003641
John McCall14606042011-06-30 08:33:18 +00003642 case TemplateName::OverloadedTemplate:
3643 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003644
John McCall14606042011-06-30 08:33:18 +00003645 case TemplateName::DependentTemplate: {
3646 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3647 assert(DTN && "Non-dependent template names must refer to template decls.");
3648 return DTN->CanonicalTemplateName;
3649 }
3650
3651 case TemplateName::SubstTemplateTemplateParm: {
3652 SubstTemplateTemplateParmStorage *subst
3653 = Name.getAsSubstTemplateTemplateParm();
3654 return getCanonicalTemplateName(subst->getReplacement());
3655 }
3656
3657 case TemplateName::SubstTemplateTemplateParmPack: {
3658 SubstTemplateTemplateParmPackStorage *subst
3659 = Name.getAsSubstTemplateTemplateParmPack();
3660 TemplateTemplateParmDecl *canonParameter
3661 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3662 TemplateArgument canonArgPack
3663 = getCanonicalTemplateArgument(subst->getArgumentPack());
3664 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3665 }
3666 }
3667
3668 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003669}
3670
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003671bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3672 X = getCanonicalTemplateName(X);
3673 Y = getCanonicalTemplateName(Y);
3674 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3675}
3676
Mike Stump1eb44332009-09-09 15:08:12 +00003677TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003678ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003679 switch (Arg.getKind()) {
3680 case TemplateArgument::Null:
3681 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Douglas Gregor1275ae02009-07-28 23:00:59 +00003683 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003684 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003685
Douglas Gregord2008e22012-04-06 22:40:38 +00003686 case TemplateArgument::Declaration: {
3687 if (Decl *D = Arg.getAsDecl())
3688 return TemplateArgument(D->getCanonicalDecl());
3689 return TemplateArgument((Decl*)0);
3690 }
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Douglas Gregor788cd062009-11-11 01:00:40 +00003692 case TemplateArgument::Template:
3693 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003694
3695 case TemplateArgument::TemplateExpansion:
3696 return TemplateArgument(getCanonicalTemplateName(
3697 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003698 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003699
Douglas Gregor1275ae02009-07-28 23:00:59 +00003700 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003701 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Douglas Gregor1275ae02009-07-28 23:00:59 +00003703 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003704 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Douglas Gregor1275ae02009-07-28 23:00:59 +00003706 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003707 if (Arg.pack_size() == 0)
3708 return Arg;
3709
Douglas Gregor910f8002010-11-07 23:05:16 +00003710 TemplateArgument *CanonArgs
3711 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003712 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003713 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003714 AEnd = Arg.pack_end();
3715 A != AEnd; (void)++A, ++Idx)
3716 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Douglas Gregor910f8002010-11-07 23:05:16 +00003718 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003719 }
3720 }
3721
3722 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003723 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003724}
3725
Douglas Gregord57959a2009-03-27 23:10:48 +00003726NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003727ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003728 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003729 return 0;
3730
3731 switch (NNS->getKind()) {
3732 case NestedNameSpecifier::Identifier:
3733 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003734 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003735 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3736 NNS->getAsIdentifier());
3737
3738 case NestedNameSpecifier::Namespace:
3739 // A namespace is canonical; build a nested-name-specifier with
3740 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003741 return NestedNameSpecifier::Create(*this, 0,
3742 NNS->getAsNamespace()->getOriginalNamespace());
3743
3744 case NestedNameSpecifier::NamespaceAlias:
3745 // A namespace is canonical; build a nested-name-specifier with
3746 // this namespace and no prefix.
3747 return NestedNameSpecifier::Create(*this, 0,
3748 NNS->getAsNamespaceAlias()->getNamespace()
3749 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003750
3751 case NestedNameSpecifier::TypeSpec:
3752 case NestedNameSpecifier::TypeSpecWithTemplate: {
3753 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003754
3755 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3756 // break it apart into its prefix and identifier, then reconsititute those
3757 // as the canonical nested-name-specifier. This is required to canonicalize
3758 // a dependent nested-name-specifier involving typedefs of dependent-name
3759 // types, e.g.,
3760 // typedef typename T::type T1;
3761 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003762 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3763 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003764 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003765
Eli Friedman16412ef2012-03-03 04:09:56 +00003766 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3767 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3768 // first place?
John McCall3b657512011-01-19 10:06:00 +00003769 return NestedNameSpecifier::Create(*this, 0, false,
3770 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003771 }
3772
3773 case NestedNameSpecifier::Global:
3774 // The global specifier is canonical and unique.
3775 return NNS;
3776 }
3777
David Blaikie7530c032012-01-17 06:56:22 +00003778 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003779}
3780
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003781
Jay Foad4ba2a172011-01-12 09:06:06 +00003782const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003783 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003784 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003785 // Handle the common positive case fast.
3786 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3787 return AT;
3788 }
Mike Stump1eb44332009-09-09 15:08:12 +00003789
John McCall0953e762009-09-24 19:53:00 +00003790 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003791 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003792 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003793
John McCall0953e762009-09-24 19:53:00 +00003794 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003795 // implements C99 6.7.3p8: "If the specification of an array type includes
3796 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003798 // If we get here, we either have type qualifiers on the type, or we have
3799 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003800 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003801
John McCall3b657512011-01-19 10:06:00 +00003802 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003803 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003804
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003805 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003806 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003807 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003808 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003810 // Otherwise, we have an array and we have qualifiers on it. Push the
3811 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003812 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003814 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3815 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3816 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003817 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003818 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3819 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3820 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003821 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003822
Mike Stump1eb44332009-09-09 15:08:12 +00003823 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003824 = dyn_cast<DependentSizedArrayType>(ATy))
3825 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003826 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003827 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003828 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003829 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003830 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003831
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003832 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003833 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003834 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003835 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003836 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003837 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003838}
3839
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003840QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003841 // C99 6.7.5.3p7:
3842 // A declaration of a parameter as "array of type" shall be
3843 // adjusted to "qualified pointer to type", where the type
3844 // qualifiers (if any) are those specified within the [ and ] of
3845 // the array type derivation.
3846 if (T->isArrayType())
3847 return getArrayDecayedType(T);
3848
3849 // C99 6.7.5.3p8:
3850 // A declaration of a parameter as "function returning type"
3851 // shall be adjusted to "pointer to function returning type", as
3852 // in 6.3.2.1.
3853 if (T->isFunctionType())
3854 return getPointerType(T);
3855
3856 return T;
3857}
3858
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003859QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003860 T = getVariableArrayDecayedType(T);
3861 T = getAdjustedParameterType(T);
3862 return T.getUnqualifiedType();
3863}
3864
Chris Lattnere6327742008-04-02 05:18:44 +00003865/// getArrayDecayedType - Return the properly qualified result of decaying the
3866/// specified array type to a pointer. This operation is non-trivial when
3867/// handling typedefs etc. The canonical type of "T" must be an array type,
3868/// this returns a pointer to a properly qualified element of the array.
3869///
3870/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003871QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003872 // Get the element type with 'getAsArrayType' so that we don't lose any
3873 // typedefs in the element type of the array. This also handles propagation
3874 // of type qualifiers from the array type into the element type if present
3875 // (C99 6.7.3p8).
3876 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3877 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003879 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003880
3881 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003882 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003883}
3884
John McCall3b657512011-01-19 10:06:00 +00003885QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3886 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003887}
3888
John McCall3b657512011-01-19 10:06:00 +00003889QualType ASTContext::getBaseElementType(QualType type) const {
3890 Qualifiers qs;
3891 while (true) {
3892 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003893 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003894 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003895
John McCall3b657512011-01-19 10:06:00 +00003896 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003897 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003898 }
Mike Stump1eb44332009-09-09 15:08:12 +00003899
John McCall3b657512011-01-19 10:06:00 +00003900 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003901}
3902
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003903/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003904uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003905ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3906 uint64_t ElementCount = 1;
3907 do {
3908 ElementCount *= CA->getSize().getZExtValue();
3909 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3910 } while (CA);
3911 return ElementCount;
3912}
3913
Reid Spencer5f016e22007-07-11 17:01:13 +00003914/// getFloatingRank - Return a relative rank for floating point types.
3915/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003916static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003917 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003918 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003919
John McCall183700f2009-09-21 23:43:11 +00003920 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3921 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003922 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003923 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003924 case BuiltinType::Float: return FloatRank;
3925 case BuiltinType::Double: return DoubleRank;
3926 case BuiltinType::LongDouble: return LongDoubleRank;
3927 }
3928}
3929
Mike Stump1eb44332009-09-09 15:08:12 +00003930/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3931/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003932/// 'typeDomain' is a real floating point or complex type.
3933/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003934QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3935 QualType Domain) const {
3936 FloatingRank EltRank = getFloatingRank(Size);
3937 if (Domain->isComplexType()) {
3938 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003939 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003940 case FloatRank: return FloatComplexTy;
3941 case DoubleRank: return DoubleComplexTy;
3942 case LongDoubleRank: return LongDoubleComplexTy;
3943 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003944 }
Chris Lattner1361b112008-04-06 23:58:54 +00003945
3946 assert(Domain->isRealFloatingType() && "Unknown domain!");
3947 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003948 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003949 case FloatRank: return FloatTy;
3950 case DoubleRank: return DoubleTy;
3951 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003952 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003953 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003954}
3955
Chris Lattner7cfeb082008-04-06 23:55:33 +00003956/// getFloatingTypeOrder - Compare the rank of the two specified floating
3957/// point types, ignoring the domain of the type (i.e. 'double' ==
3958/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003959/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003960int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003961 FloatingRank LHSR = getFloatingRank(LHS);
3962 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Chris Lattnera75cea32008-04-06 23:38:49 +00003964 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003965 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003966 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003967 return 1;
3968 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003969}
3970
Chris Lattnerf52ab252008-04-06 22:59:24 +00003971/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3972/// routine will assert if passed a built-in type that isn't an integer or enum,
3973/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003974unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003975 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003976
Chris Lattnerf52ab252008-04-06 22:59:24 +00003977 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003978 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003979 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003980 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003981 case BuiltinType::Char_S:
3982 case BuiltinType::Char_U:
3983 case BuiltinType::SChar:
3984 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003985 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003986 case BuiltinType::Short:
3987 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003988 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003989 case BuiltinType::Int:
3990 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003991 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003992 case BuiltinType::Long:
3993 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003994 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003995 case BuiltinType::LongLong:
3996 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003997 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003998 case BuiltinType::Int128:
3999 case BuiltinType::UInt128:
4000 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004001 }
4002}
4003
Eli Friedman04e83572009-08-20 04:21:42 +00004004/// \brief Whether this is a promotable bitfield reference according
4005/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4006///
4007/// \returns the type this bit-field will promote to, or NULL if no
4008/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004009QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004010 if (E->isTypeDependent() || E->isValueDependent())
4011 return QualType();
4012
Eli Friedman04e83572009-08-20 04:21:42 +00004013 FieldDecl *Field = E->getBitField();
4014 if (!Field)
4015 return QualType();
4016
4017 QualType FT = Field->getType();
4018
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004019 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004020 uint64_t IntSize = getTypeSize(IntTy);
4021 // GCC extension compatibility: if the bit-field size is less than or equal
4022 // to the size of int, it gets promoted no matter what its type is.
4023 // For instance, unsigned long bf : 4 gets promoted to signed int.
4024 if (BitWidth < IntSize)
4025 return IntTy;
4026
4027 if (BitWidth == IntSize)
4028 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4029
4030 // Types bigger than int are not subject to promotions, and therefore act
4031 // like the base type.
4032 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4033 // is ridiculous.
4034 return QualType();
4035}
4036
Eli Friedmana95d7572009-08-19 07:44:53 +00004037/// getPromotedIntegerType - Returns the type that Promotable will
4038/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4039/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004040QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004041 assert(!Promotable.isNull());
4042 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004043 if (const EnumType *ET = Promotable->getAs<EnumType>())
4044 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004045
4046 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4047 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4048 // (3.9.1) can be converted to a prvalue of the first of the following
4049 // types that can represent all the values of its underlying type:
4050 // int, unsigned int, long int, unsigned long int, long long int, or
4051 // unsigned long long int [...]
4052 // FIXME: Is there some better way to compute this?
4053 if (BT->getKind() == BuiltinType::WChar_S ||
4054 BT->getKind() == BuiltinType::WChar_U ||
4055 BT->getKind() == BuiltinType::Char16 ||
4056 BT->getKind() == BuiltinType::Char32) {
4057 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4058 uint64_t FromSize = getTypeSize(BT);
4059 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4060 LongLongTy, UnsignedLongLongTy };
4061 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4062 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4063 if (FromSize < ToSize ||
4064 (FromSize == ToSize &&
4065 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4066 return PromoteTypes[Idx];
4067 }
4068 llvm_unreachable("char type should fit into long long");
4069 }
4070 }
4071
4072 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004073 if (Promotable->isSignedIntegerType())
4074 return IntTy;
4075 uint64_t PromotableSize = getTypeSize(Promotable);
4076 uint64_t IntSize = getTypeSize(IntTy);
4077 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4078 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4079}
4080
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004081/// \brief Recurses in pointer/array types until it finds an objc retainable
4082/// type and returns its ownership.
4083Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4084 while (!T.isNull()) {
4085 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4086 return T.getObjCLifetime();
4087 if (T->isArrayType())
4088 T = getBaseElementType(T);
4089 else if (const PointerType *PT = T->getAs<PointerType>())
4090 T = PT->getPointeeType();
4091 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004092 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004093 else
4094 break;
4095 }
4096
4097 return Qualifiers::OCL_None;
4098}
4099
Mike Stump1eb44332009-09-09 15:08:12 +00004100/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004101/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004102/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004103int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004104 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4105 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004106 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004107
Chris Lattnerf52ab252008-04-06 22:59:24 +00004108 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4109 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Chris Lattner7cfeb082008-04-06 23:55:33 +00004111 unsigned LHSRank = getIntegerRank(LHSC);
4112 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Chris Lattner7cfeb082008-04-06 23:55:33 +00004114 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4115 if (LHSRank == RHSRank) return 0;
4116 return LHSRank > RHSRank ? 1 : -1;
4117 }
Mike Stump1eb44332009-09-09 15:08:12 +00004118
Chris Lattner7cfeb082008-04-06 23:55:33 +00004119 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4120 if (LHSUnsigned) {
4121 // If the unsigned [LHS] type is larger, return it.
4122 if (LHSRank >= RHSRank)
4123 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Chris Lattner7cfeb082008-04-06 23:55:33 +00004125 // If the signed type can represent all values of the unsigned type, it
4126 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004127 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004128 return -1;
4129 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004130
Chris Lattner7cfeb082008-04-06 23:55:33 +00004131 // If the unsigned [RHS] type is larger, return it.
4132 if (RHSRank >= LHSRank)
4133 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Chris Lattner7cfeb082008-04-06 23:55:33 +00004135 // If the signed type can represent all values of the unsigned type, it
4136 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004137 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004138 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004139}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004140
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004141static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004142CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4143 DeclContext *DC, IdentifierInfo *Id) {
4144 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004145 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004146 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004147 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004148 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004149}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004150
Mike Stump1eb44332009-09-09 15:08:12 +00004151// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004152QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004153 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004154 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004155 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004156 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004157 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004158
Anders Carlssonf06273f2007-11-19 00:25:30 +00004159 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004160
Anders Carlsson71993dd2007-08-17 05:31:46 +00004161 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004162 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004163 // int flags;
4164 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004165 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004166 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004167 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004168 FieldTypes[3] = LongTy;
4169
Anders Carlsson71993dd2007-08-17 05:31:46 +00004170 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004171 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004172 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004173 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004174 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004175 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004176 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004177 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004178 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004179 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004180 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004181 }
4182
Douglas Gregor838db382010-02-11 01:19:42 +00004183 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004184 }
Mike Stump1eb44332009-09-09 15:08:12 +00004185
Anders Carlsson71993dd2007-08-17 05:31:46 +00004186 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004187}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004188
Douglas Gregor319ac892009-04-23 22:29:11 +00004189void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004190 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004191 assert(Rec && "Invalid CFConstantStringType");
4192 CFConstantStringTypeDecl = Rec->getDecl();
4193}
4194
Jay Foad4ba2a172011-01-12 09:06:06 +00004195QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004196 if (BlockDescriptorType)
4197 return getTagDeclType(BlockDescriptorType);
4198
4199 RecordDecl *T;
4200 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004201 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004202 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004203 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004204
4205 QualType FieldTypes[] = {
4206 UnsignedLongTy,
4207 UnsignedLongTy,
4208 };
4209
4210 const char *FieldNames[] = {
4211 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004212 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004213 };
4214
4215 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004216 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004217 SourceLocation(),
4218 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004219 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004220 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004221 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004222 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004223 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004224 T->addDecl(Field);
4225 }
4226
Douglas Gregor838db382010-02-11 01:19:42 +00004227 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004228
4229 BlockDescriptorType = T;
4230
4231 return getTagDeclType(BlockDescriptorType);
4232}
4233
Jay Foad4ba2a172011-01-12 09:06:06 +00004234QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004235 if (BlockDescriptorExtendedType)
4236 return getTagDeclType(BlockDescriptorExtendedType);
4237
4238 RecordDecl *T;
4239 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004240 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004241 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004242 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004243
4244 QualType FieldTypes[] = {
4245 UnsignedLongTy,
4246 UnsignedLongTy,
4247 getPointerType(VoidPtrTy),
4248 getPointerType(VoidPtrTy)
4249 };
4250
4251 const char *FieldNames[] = {
4252 "reserved",
4253 "Size",
4254 "CopyFuncPtr",
4255 "DestroyFuncPtr"
4256 };
4257
4258 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004259 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004260 SourceLocation(),
4261 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004262 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004263 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004264 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004265 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004266 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004267 T->addDecl(Field);
4268 }
4269
Douglas Gregor838db382010-02-11 01:19:42 +00004270 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004271
4272 BlockDescriptorExtendedType = T;
4273
4274 return getTagDeclType(BlockDescriptorExtendedType);
4275}
4276
Jay Foad4ba2a172011-01-12 09:06:06 +00004277bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00004278 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004279 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00004280 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004281 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4282 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00004283 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004284
4285 }
4286 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004287 return false;
4288}
4289
Jay Foad4ba2a172011-01-12 09:06:06 +00004290QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00004291ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004292 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00004293 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004294 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00004295 // unsigned int __flags;
4296 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00004297 // void *__copy_helper; // as needed
4298 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004299 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00004300 // } *
4301
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004302 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4303
4304 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004305 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00004306 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4307 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004308 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004309 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004310 T->startDefinition();
4311 QualType Int32Ty = IntTy;
4312 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4313 QualType FieldTypes[] = {
4314 getPointerType(VoidPtrTy),
4315 getPointerType(getTagDeclType(T)),
4316 Int32Ty,
4317 Int32Ty,
4318 getPointerType(VoidPtrTy),
4319 getPointerType(VoidPtrTy),
4320 Ty
4321 };
4322
Chris Lattner5f9e2722011-07-23 10:55:15 +00004323 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004324 "__isa",
4325 "__forwarding",
4326 "__flags",
4327 "__size",
4328 "__copy_helper",
4329 "__destroy_helper",
4330 DeclName,
4331 };
4332
4333 for (size_t i = 0; i < 7; ++i) {
4334 if (!HasCopyAndDispose && i >=4 && i <= 5)
4335 continue;
4336 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004337 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004338 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004339 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004340 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004341 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004342 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004343 T->addDecl(Field);
4344 }
4345
Douglas Gregor838db382010-02-11 01:19:42 +00004346 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004347
4348 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004349}
4350
Douglas Gregore97179c2011-09-08 01:46:34 +00004351TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4352 if (!ObjCInstanceTypeDecl)
4353 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4354 getTranslationUnitDecl(),
4355 SourceLocation(),
4356 SourceLocation(),
4357 &Idents.get("instancetype"),
4358 getTrivialTypeSourceInfo(getObjCIdType()));
4359 return ObjCInstanceTypeDecl;
4360}
4361
Anders Carlssone8c49532007-10-29 06:33:42 +00004362// This returns true if a type has been typedefed to BOOL:
4363// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004364static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004365 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004366 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4367 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004369 return false;
4370}
4371
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004372/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004373/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004374CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004375 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4376 return CharUnits::Zero();
4377
Ken Dyck199c3d62010-01-11 17:06:35 +00004378 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004380 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004381 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004382 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004383 // Treat arrays as pointers, since that's how they're passed in.
4384 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004385 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004386 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004387}
4388
4389static inline
4390std::string charUnitsToString(const CharUnits &CU) {
4391 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004392}
4393
John McCall6b5a61b2011-02-07 10:33:21 +00004394/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004395/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004396std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4397 std::string S;
4398
David Chisnall5e530af2009-11-17 19:33:30 +00004399 const BlockDecl *Decl = Expr->getBlockDecl();
4400 QualType BlockTy =
4401 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4402 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004403 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004404 // Compute size of all parameters.
4405 // Start with computing size of a pointer in number of bytes.
4406 // FIXME: There might(should) be a better way of doing this computation!
4407 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004408 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4409 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004410 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004411 E = Decl->param_end(); PI != E; ++PI) {
4412 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004413 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004414 if (sz.isZero())
4415 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004416 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004417 ParmOffset += sz;
4418 }
4419 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004420 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004421 // Block pointer and offset.
4422 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004423
4424 // Argument types.
4425 ParmOffset = PtrSize;
4426 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4427 Decl->param_end(); PI != E; ++PI) {
4428 ParmVarDecl *PVDecl = *PI;
4429 QualType PType = PVDecl->getOriginalType();
4430 if (const ArrayType *AT =
4431 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4432 // Use array's original type only if it has known number of
4433 // elements.
4434 if (!isa<ConstantArrayType>(AT))
4435 PType = PVDecl->getType();
4436 } else if (PType->isFunctionType())
4437 PType = PVDecl->getType();
4438 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004439 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004440 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004441 }
John McCall6b5a61b2011-02-07 10:33:21 +00004442
4443 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004444}
4445
Douglas Gregorf968d832011-05-27 01:19:52 +00004446bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004447 std::string& S) {
4448 // Encode result type.
4449 getObjCEncodingForType(Decl->getResultType(), S);
4450 CharUnits ParmOffset;
4451 // Compute size of all parameters.
4452 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4453 E = Decl->param_end(); PI != E; ++PI) {
4454 QualType PType = (*PI)->getType();
4455 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004456 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004457 continue;
4458
David Chisnall5389f482010-12-30 14:05:53 +00004459 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004460 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004461 ParmOffset += sz;
4462 }
4463 S += charUnitsToString(ParmOffset);
4464 ParmOffset = CharUnits::Zero();
4465
4466 // Argument types.
4467 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4468 E = Decl->param_end(); PI != E; ++PI) {
4469 ParmVarDecl *PVDecl = *PI;
4470 QualType PType = PVDecl->getOriginalType();
4471 if (const ArrayType *AT =
4472 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4473 // Use array's original type only if it has known number of
4474 // elements.
4475 if (!isa<ConstantArrayType>(AT))
4476 PType = PVDecl->getType();
4477 } else if (PType->isFunctionType())
4478 PType = PVDecl->getType();
4479 getObjCEncodingForType(PType, S);
4480 S += charUnitsToString(ParmOffset);
4481 ParmOffset += getObjCEncodingTypeSize(PType);
4482 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004483
4484 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004485}
4486
Bob Wilsondc8dab62011-11-30 01:57:58 +00004487/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4488/// method parameter or return type. If Extended, include class names and
4489/// block object types.
4490void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4491 QualType T, std::string& S,
4492 bool Extended) const {
4493 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4494 getObjCEncodingForTypeQualifier(QT, S);
4495 // Encode parameter type.
4496 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4497 true /*OutermostType*/,
4498 false /*EncodingProperty*/,
4499 false /*StructField*/,
4500 Extended /*EncodeBlockParameters*/,
4501 Extended /*EncodeClassNames*/);
4502}
4503
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004504/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004505/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004506bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004507 std::string& S,
4508 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004509 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004510 // Encode return type.
4511 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4512 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004513 // Compute size of all parameters.
4514 // Start with computing size of a pointer in number of bytes.
4515 // FIXME: There might(should) be a better way of doing this computation!
4516 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004517 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004518 // The first two arguments (self and _cmd) are pointers; account for
4519 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004520 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004521 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004522 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004523 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004524 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004525 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004526 continue;
4527
Ken Dyck199c3d62010-01-11 17:06:35 +00004528 assert (sz.isPositive() &&
4529 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004530 ParmOffset += sz;
4531 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004532 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004533 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004534 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004536 // Argument types.
4537 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004538 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004539 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004540 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004541 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004542 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004543 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4544 // Use array's original type only if it has known number of
4545 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004546 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004547 PType = PVDecl->getType();
4548 } else if (PType->isFunctionType())
4549 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004550 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4551 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004552 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004553 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004554 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004555
4556 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004557}
4558
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004559/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004560/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004561/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4562/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004563/// Property attributes are stored as a comma-delimited C string. The simple
4564/// attributes readonly and bycopy are encoded as single characters. The
4565/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4566/// encoded as single characters, followed by an identifier. Property types
4567/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004568/// these attributes are defined by the following enumeration:
4569/// @code
4570/// enum PropertyAttributes {
4571/// kPropertyReadOnly = 'R', // property is read-only.
4572/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4573/// kPropertyByref = '&', // property is a reference to the value last assigned
4574/// kPropertyDynamic = 'D', // property is dynamic
4575/// kPropertyGetter = 'G', // followed by getter selector name
4576/// kPropertySetter = 'S', // followed by setter selector name
4577/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004578/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004579/// kPropertyWeak = 'W' // 'weak' property
4580/// kPropertyStrong = 'P' // property GC'able
4581/// kPropertyNonAtomic = 'N' // property non-atomic
4582/// };
4583/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004584void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004585 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004586 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004587 // Collect information from the property implementation decl(s).
4588 bool Dynamic = false;
4589 ObjCPropertyImplDecl *SynthesizePID = 0;
4590
4591 // FIXME: Duplicated code due to poor abstraction.
4592 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004593 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004594 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4595 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004596 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004597 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004598 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004599 if (PID->getPropertyDecl() == PD) {
4600 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4601 Dynamic = true;
4602 } else {
4603 SynthesizePID = PID;
4604 }
4605 }
4606 }
4607 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004608 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004609 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004610 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004611 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004612 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004613 if (PID->getPropertyDecl() == PD) {
4614 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4615 Dynamic = true;
4616 } else {
4617 SynthesizePID = PID;
4618 }
4619 }
Mike Stump1eb44332009-09-09 15:08:12 +00004620 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004621 }
4622 }
4623
4624 // FIXME: This is not very efficient.
4625 S = "T";
4626
4627 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004628 // GCC has some special rules regarding encoding of properties which
4629 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004630 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004631 true /* outermost type */,
4632 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004633
4634 if (PD->isReadOnly()) {
4635 S += ",R";
4636 } else {
4637 switch (PD->getSetterKind()) {
4638 case ObjCPropertyDecl::Assign: break;
4639 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004640 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004641 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004642 }
4643 }
4644
4645 // It really isn't clear at all what this means, since properties
4646 // are "dynamic by default".
4647 if (Dynamic)
4648 S += ",D";
4649
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004650 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4651 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004652
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004653 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4654 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004655 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004656 }
4657
4658 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4659 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004660 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004661 }
4662
4663 if (SynthesizePID) {
4664 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4665 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004666 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004667 }
4668
4669 // FIXME: OBJCGC: weak & strong
4670}
4671
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004672/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004673/// Another legacy compatibility encoding: 32-bit longs are encoded as
4674/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004675/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4676///
4677void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004678 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004679 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004680 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004681 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004682 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004683 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004684 PointeeTy = IntTy;
4685 }
4686 }
4687}
4688
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004689void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004690 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004691 // We follow the behavior of gcc, expanding structures which are
4692 // directly pointed to, and expanding embedded structures. Note that
4693 // these rules are sufficient to prevent recursive encoding of the
4694 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004695 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004696 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004697}
4698
David Chisnall64fd7e82010-06-04 01:10:52 +00004699static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4700 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004701 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004702 case BuiltinType::Void: return 'v';
4703 case BuiltinType::Bool: return 'B';
4704 case BuiltinType::Char_U:
4705 case BuiltinType::UChar: return 'C';
4706 case BuiltinType::UShort: return 'S';
4707 case BuiltinType::UInt: return 'I';
4708 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004709 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004710 case BuiltinType::UInt128: return 'T';
4711 case BuiltinType::ULongLong: return 'Q';
4712 case BuiltinType::Char_S:
4713 case BuiltinType::SChar: return 'c';
4714 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004715 case BuiltinType::WChar_S:
4716 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004717 case BuiltinType::Int: return 'i';
4718 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004719 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004720 case BuiltinType::LongLong: return 'q';
4721 case BuiltinType::Int128: return 't';
4722 case BuiltinType::Float: return 'f';
4723 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004724 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004725 }
4726}
4727
Douglas Gregor5471bc82011-09-08 17:18:35 +00004728static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4729 EnumDecl *Enum = ET->getDecl();
4730
4731 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4732 if (!Enum->isFixed())
4733 return 'i';
4734
4735 // The encoding of a fixed enum type matches its fixed underlying type.
4736 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4737}
4738
Jay Foad4ba2a172011-01-12 09:06:06 +00004739static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004740 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004741 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004742 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004743 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4744 // The GNU runtime requires more information; bitfields are encoded as b,
4745 // then the offset (in bits) of the first element, then the type of the
4746 // bitfield, then the size in bits. For example, in this structure:
4747 //
4748 // struct
4749 // {
4750 // int integer;
4751 // int flags:2;
4752 // };
4753 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4754 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4755 // information is not especially sensible, but we're stuck with it for
4756 // compatibility with GCC, although providing it breaks anything that
4757 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004758 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004759 const RecordDecl *RD = FD->getParent();
4760 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004761 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004762 if (const EnumType *ET = T->getAs<EnumType>())
4763 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004764 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004765 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004766 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004767 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004768}
4769
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004770// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004771void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4772 bool ExpandPointedToStructures,
4773 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004774 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004775 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004776 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004777 bool StructField,
4778 bool EncodeBlockParameters,
4779 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004780 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004781 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004782 return EncodeBitField(this, S, T, FD);
4783 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004784 return;
4785 }
Mike Stump1eb44332009-09-09 15:08:12 +00004786
John McCall183700f2009-09-21 23:43:11 +00004787 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004788 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004789 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004790 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004791 return;
4792 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004793
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004794 // encoding for pointer or r3eference types.
4795 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004796 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004797 if (PT->isObjCSelType()) {
4798 S += ':';
4799 return;
4800 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004801 PointeeTy = PT->getPointeeType();
4802 }
4803 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4804 PointeeTy = RT->getPointeeType();
4805 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004806 bool isReadOnly = false;
4807 // For historical/compatibility reasons, the read-only qualifier of the
4808 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4809 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004810 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004811 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004812 if (OutermostType && T.isConstQualified()) {
4813 isReadOnly = true;
4814 S += 'r';
4815 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004816 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004817 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004818 while (P->getAs<PointerType>())
4819 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004820 if (P.isConstQualified()) {
4821 isReadOnly = true;
4822 S += 'r';
4823 }
4824 }
4825 if (isReadOnly) {
4826 // Another legacy compatibility encoding. Some ObjC qualifier and type
4827 // combinations need to be rearranged.
4828 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004829 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004830 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004831 }
Mike Stump1eb44332009-09-09 15:08:12 +00004832
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004833 if (PointeeTy->isCharType()) {
4834 // char pointer types should be encoded as '*' unless it is a
4835 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004836 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004837 S += '*';
4838 return;
4839 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004840 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004841 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4842 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4843 S += '#';
4844 return;
4845 }
4846 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4847 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4848 S += '@';
4849 return;
4850 }
4851 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004852 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004853 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004854 getLegacyIntegralTypeEncoding(PointeeTy);
4855
Mike Stump1eb44332009-09-09 15:08:12 +00004856 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004857 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004858 return;
4859 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004860
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004861 if (const ArrayType *AT =
4862 // Ignore type qualifiers etc.
4863 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004864 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004865 // Incomplete arrays are encoded as a pointer to the array element.
4866 S += '^';
4867
Mike Stump1eb44332009-09-09 15:08:12 +00004868 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004869 false, ExpandStructures, FD);
4870 } else {
4871 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004872
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004873 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4874 if (getTypeSize(CAT->getElementType()) == 0)
4875 S += '0';
4876 else
4877 S += llvm::utostr(CAT->getSize().getZExtValue());
4878 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004879 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004880 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4881 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004882 S += '0';
4883 }
Mike Stump1eb44332009-09-09 15:08:12 +00004884
4885 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004886 false, ExpandStructures, FD);
4887 S += ']';
4888 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004889 return;
4890 }
Mike Stump1eb44332009-09-09 15:08:12 +00004891
John McCall183700f2009-09-21 23:43:11 +00004892 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004893 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004894 return;
4895 }
Mike Stump1eb44332009-09-09 15:08:12 +00004896
Ted Kremenek6217b802009-07-29 21:53:49 +00004897 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004898 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004899 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004900 // Anonymous structures print as '?'
4901 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4902 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004903 if (ClassTemplateSpecializationDecl *Spec
4904 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4905 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4906 std::string TemplateArgsStr
4907 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004908 TemplateArgs.data(),
4909 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004910 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004911
4912 S += TemplateArgsStr;
4913 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004914 } else {
4915 S += '?';
4916 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004917 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004918 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004919 if (!RDecl->isUnion()) {
4920 getObjCEncodingForStructureImpl(RDecl, S, FD);
4921 } else {
4922 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4923 FieldEnd = RDecl->field_end();
4924 Field != FieldEnd; ++Field) {
4925 if (FD) {
4926 S += '"';
4927 S += Field->getNameAsString();
4928 S += '"';
4929 }
Mike Stump1eb44332009-09-09 15:08:12 +00004930
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004931 // Special case bit-fields.
4932 if (Field->isBitField()) {
4933 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00004934 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004935 } else {
4936 QualType qt = Field->getType();
4937 getLegacyIntegralTypeEncoding(qt);
4938 getObjCEncodingForTypeImpl(qt, S, false, true,
4939 FD, /*OutermostType*/false,
4940 /*EncodingProperty*/false,
4941 /*StructField*/true);
4942 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004943 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004944 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004945 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004946 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004947 return;
4948 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004949
Douglas Gregor5471bc82011-09-08 17:18:35 +00004950 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004951 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004952 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004953 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004954 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004955 return;
4956 }
Mike Stump1eb44332009-09-09 15:08:12 +00004957
Bob Wilsondc8dab62011-11-30 01:57:58 +00004958 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004959 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004960 if (EncodeBlockParameters) {
4961 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4962
4963 S += '<';
4964 // Block return type
4965 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4966 ExpandPointedToStructures, ExpandStructures,
4967 FD,
4968 false /* OutermostType */,
4969 EncodingProperty,
4970 false /* StructField */,
4971 EncodeBlockParameters,
4972 EncodeClassNames);
4973 // Block self
4974 S += "@?";
4975 // Block parameters
4976 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4977 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4978 E = FPT->arg_type_end(); I && (I != E); ++I) {
4979 getObjCEncodingForTypeImpl(*I, S,
4980 ExpandPointedToStructures,
4981 ExpandStructures,
4982 FD,
4983 false /* OutermostType */,
4984 EncodingProperty,
4985 false /* StructField */,
4986 EncodeBlockParameters,
4987 EncodeClassNames);
4988 }
4989 }
4990 S += '>';
4991 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004992 return;
4993 }
Mike Stump1eb44332009-09-09 15:08:12 +00004994
John McCallc12c5bb2010-05-15 11:32:37 +00004995 // Ignore protocol qualifiers when mangling at this level.
4996 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4997 T = OT->getBaseType();
4998
John McCall0953e762009-09-24 19:53:00 +00004999 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005000 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005001 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005002 S += '{';
5003 const IdentifierInfo *II = OI->getIdentifier();
5004 S += II->getName();
5005 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005006 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005007 DeepCollectObjCIvars(OI, true, Ivars);
5008 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005009 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005010 if (Field->isBitField())
5011 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005012 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005013 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005014 }
5015 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005016 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005017 }
Mike Stump1eb44332009-09-09 15:08:12 +00005018
John McCall183700f2009-09-21 23:43:11 +00005019 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00005020 if (OPT->isObjCIdType()) {
5021 S += '@';
5022 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005023 }
Mike Stump1eb44332009-09-09 15:08:12 +00005024
Steve Naroff27d20a22009-10-28 22:03:49 +00005025 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5026 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5027 // Since this is a binary compatibility issue, need to consult with runtime
5028 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005029 S += '#';
5030 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005031 }
Mike Stump1eb44332009-09-09 15:08:12 +00005032
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005033 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005034 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005035 ExpandPointedToStructures,
5036 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005037 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005038 // Note that we do extended encoding of protocol qualifer list
5039 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005040 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005041 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5042 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005043 S += '<';
5044 S += (*I)->getNameAsString();
5045 S += '>';
5046 }
5047 S += '"';
5048 }
5049 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005050 }
Mike Stump1eb44332009-09-09 15:08:12 +00005051
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005052 QualType PointeeTy = OPT->getPointeeType();
5053 if (!EncodingProperty &&
5054 isa<TypedefType>(PointeeTy.getTypePtr())) {
5055 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005056 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005057 // {...};
5058 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005059 getObjCEncodingForTypeImpl(PointeeTy, S,
5060 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005061 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00005062 return;
5063 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005064
5065 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005066 if (OPT->getInterfaceDecl() &&
5067 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005068 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005069 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005070 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5071 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005072 S += '<';
5073 S += (*I)->getNameAsString();
5074 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005075 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005076 S += '"';
5077 }
5078 return;
5079 }
Mike Stump1eb44332009-09-09 15:08:12 +00005080
John McCall532ec7b2010-05-17 23:56:34 +00005081 // gcc just blithely ignores member pointers.
5082 // TODO: maybe there should be a mangling for these
5083 if (T->getAs<MemberPointerType>())
5084 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005085
5086 if (T->isVectorType()) {
5087 // This matches gcc's encoding, even though technically it is
5088 // insufficient.
5089 // FIXME. We should do a better job than gcc.
5090 return;
5091 }
5092
David Blaikieb219cfc2011-09-23 05:06:16 +00005093 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005094}
5095
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005096void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5097 std::string &S,
5098 const FieldDecl *FD,
5099 bool includeVBases) const {
5100 assert(RDecl && "Expected non-null RecordDecl");
5101 assert(!RDecl->isUnion() && "Should not be called for unions");
5102 if (!RDecl->getDefinition())
5103 return;
5104
5105 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5106 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5107 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5108
5109 if (CXXRec) {
5110 for (CXXRecordDecl::base_class_iterator
5111 BI = CXXRec->bases_begin(),
5112 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5113 if (!BI->isVirtual()) {
5114 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005115 if (base->isEmpty())
5116 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005117 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005118 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5119 std::make_pair(offs, base));
5120 }
5121 }
5122 }
5123
5124 unsigned i = 0;
5125 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5126 FieldEnd = RDecl->field_end();
5127 Field != FieldEnd; ++Field, ++i) {
5128 uint64_t offs = layout.getFieldOffset(i);
5129 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005130 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005131 }
5132
5133 if (CXXRec && includeVBases) {
5134 for (CXXRecordDecl::base_class_iterator
5135 BI = CXXRec->vbases_begin(),
5136 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5137 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005138 if (base->isEmpty())
5139 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005140 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005141 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5142 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5143 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005144 }
5145 }
5146
5147 CharUnits size;
5148 if (CXXRec) {
5149 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5150 } else {
5151 size = layout.getSize();
5152 }
5153
5154 uint64_t CurOffs = 0;
5155 std::multimap<uint64_t, NamedDecl *>::iterator
5156 CurLayObj = FieldOrBaseOffsets.begin();
5157
Douglas Gregor58db7a52012-04-27 22:30:01 +00005158 if (CXXRec && CXXRec->isDynamicClass() &&
5159 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005160 if (FD) {
5161 S += "\"_vptr$";
5162 std::string recname = CXXRec->getNameAsString();
5163 if (recname.empty()) recname = "?";
5164 S += recname;
5165 S += '"';
5166 }
5167 S += "^^?";
5168 CurOffs += getTypeSize(VoidPtrTy);
5169 }
5170
5171 if (!RDecl->hasFlexibleArrayMember()) {
5172 // Mark the end of the structure.
5173 uint64_t offs = toBits(size);
5174 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5175 std::make_pair(offs, (NamedDecl*)0));
5176 }
5177
5178 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5179 assert(CurOffs <= CurLayObj->first);
5180
5181 if (CurOffs < CurLayObj->first) {
5182 uint64_t padding = CurLayObj->first - CurOffs;
5183 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5184 // packing/alignment of members is different that normal, in which case
5185 // the encoding will be out-of-sync with the real layout.
5186 // If the runtime switches to just consider the size of types without
5187 // taking into account alignment, we could make padding explicit in the
5188 // encoding (e.g. using arrays of chars). The encoding strings would be
5189 // longer then though.
5190 CurOffs += padding;
5191 }
5192
5193 NamedDecl *dcl = CurLayObj->second;
5194 if (dcl == 0)
5195 break; // reached end of structure.
5196
5197 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5198 // We expand the bases without their virtual bases since those are going
5199 // in the initial structure. Note that this differs from gcc which
5200 // expands virtual bases each time one is encountered in the hierarchy,
5201 // making the encoding type bigger than it really is.
5202 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005203 assert(!base->isEmpty());
5204 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005205 } else {
5206 FieldDecl *field = cast<FieldDecl>(dcl);
5207 if (FD) {
5208 S += '"';
5209 S += field->getNameAsString();
5210 S += '"';
5211 }
5212
5213 if (field->isBitField()) {
5214 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005215 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005216 } else {
5217 QualType qt = field->getType();
5218 getLegacyIntegralTypeEncoding(qt);
5219 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5220 /*OutermostType*/false,
5221 /*EncodingProperty*/false,
5222 /*StructField*/true);
5223 CurOffs += getTypeSize(field->getType());
5224 }
5225 }
5226 }
5227}
5228
Mike Stump1eb44332009-09-09 15:08:12 +00005229void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005230 std::string& S) const {
5231 if (QT & Decl::OBJC_TQ_In)
5232 S += 'n';
5233 if (QT & Decl::OBJC_TQ_Inout)
5234 S += 'N';
5235 if (QT & Decl::OBJC_TQ_Out)
5236 S += 'o';
5237 if (QT & Decl::OBJC_TQ_Bycopy)
5238 S += 'O';
5239 if (QT & Decl::OBJC_TQ_Byref)
5240 S += 'R';
5241 if (QT & Decl::OBJC_TQ_Oneway)
5242 S += 'V';
5243}
5244
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005245TypedefDecl *ASTContext::getObjCIdDecl() const {
5246 if (!ObjCIdDecl) {
5247 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5248 T = getObjCObjectPointerType(T);
5249 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5250 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5251 getTranslationUnitDecl(),
5252 SourceLocation(), SourceLocation(),
5253 &Idents.get("id"), IdInfo);
5254 }
5255
5256 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005257}
5258
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005259TypedefDecl *ASTContext::getObjCSelDecl() const {
5260 if (!ObjCSelDecl) {
5261 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5262 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5263 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5264 getTranslationUnitDecl(),
5265 SourceLocation(), SourceLocation(),
5266 &Idents.get("SEL"), SelInfo);
5267 }
5268 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005269}
5270
Douglas Gregor79d67262011-08-12 05:59:41 +00005271TypedefDecl *ASTContext::getObjCClassDecl() const {
5272 if (!ObjCClassDecl) {
5273 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5274 T = getObjCObjectPointerType(T);
5275 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5276 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5277 getTranslationUnitDecl(),
5278 SourceLocation(), SourceLocation(),
5279 &Idents.get("Class"), ClassInfo);
5280 }
5281
5282 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005283}
5284
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005285ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5286 if (!ObjCProtocolClassDecl) {
5287 ObjCProtocolClassDecl
5288 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5289 SourceLocation(),
5290 &Idents.get("Protocol"),
5291 /*PrevDecl=*/0,
5292 SourceLocation(), true);
5293 }
5294
5295 return ObjCProtocolClassDecl;
5296}
5297
Meador Ingec5613b22012-06-16 03:34:49 +00005298//===----------------------------------------------------------------------===//
5299// __builtin_va_list Construction Functions
5300//===----------------------------------------------------------------------===//
5301
5302static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5303 // typedef char* __builtin_va_list;
5304 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5305 TypeSourceInfo *TInfo
5306 = Context->getTrivialTypeSourceInfo(CharPtrType);
5307
5308 TypedefDecl *VaListTypeDecl
5309 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5310 Context->getTranslationUnitDecl(),
5311 SourceLocation(), SourceLocation(),
5312 &Context->Idents.get("__builtin_va_list"),
5313 TInfo);
5314 return VaListTypeDecl;
5315}
5316
5317static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5318 // typedef void* __builtin_va_list;
5319 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5320 TypeSourceInfo *TInfo
5321 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5322
5323 TypedefDecl *VaListTypeDecl
5324 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5325 Context->getTranslationUnitDecl(),
5326 SourceLocation(), SourceLocation(),
5327 &Context->Idents.get("__builtin_va_list"),
5328 TInfo);
5329 return VaListTypeDecl;
5330}
5331
5332static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5333 // typedef struct __va_list_tag {
5334 RecordDecl *VaListTagDecl;
5335
5336 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5337 Context->getTranslationUnitDecl(),
5338 &Context->Idents.get("__va_list_tag"));
5339 VaListTagDecl->startDefinition();
5340
5341 const size_t NumFields = 5;
5342 QualType FieldTypes[NumFields];
5343 const char *FieldNames[NumFields];
5344
5345 // unsigned char gpr;
5346 FieldTypes[0] = Context->UnsignedCharTy;
5347 FieldNames[0] = "gpr";
5348
5349 // unsigned char fpr;
5350 FieldTypes[1] = Context->UnsignedCharTy;
5351 FieldNames[1] = "fpr";
5352
5353 // unsigned short reserved;
5354 FieldTypes[2] = Context->UnsignedShortTy;
5355 FieldNames[2] = "reserved";
5356
5357 // void* overflow_arg_area;
5358 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5359 FieldNames[3] = "overflow_arg_area";
5360
5361 // void* reg_save_area;
5362 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5363 FieldNames[4] = "reg_save_area";
5364
5365 // Create fields
5366 for (unsigned i = 0; i < NumFields; ++i) {
5367 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5368 SourceLocation(),
5369 SourceLocation(),
5370 &Context->Idents.get(FieldNames[i]),
5371 FieldTypes[i], /*TInfo=*/0,
5372 /*BitWidth=*/0,
5373 /*Mutable=*/false,
5374 ICIS_NoInit);
5375 Field->setAccess(AS_public);
5376 VaListTagDecl->addDecl(Field);
5377 }
5378 VaListTagDecl->completeDefinition();
5379 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005380 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005381
5382 // } __va_list_tag;
5383 TypedefDecl *VaListTagTypedefDecl
5384 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5385 Context->getTranslationUnitDecl(),
5386 SourceLocation(), SourceLocation(),
5387 &Context->Idents.get("__va_list_tag"),
5388 Context->getTrivialTypeSourceInfo(VaListTagType));
5389 QualType VaListTagTypedefType =
5390 Context->getTypedefType(VaListTagTypedefDecl);
5391
5392 // typedef __va_list_tag __builtin_va_list[1];
5393 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5394 QualType VaListTagArrayType
5395 = Context->getConstantArrayType(VaListTagTypedefType,
5396 Size, ArrayType::Normal, 0);
5397 TypeSourceInfo *TInfo
5398 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5399 TypedefDecl *VaListTypedefDecl
5400 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5401 Context->getTranslationUnitDecl(),
5402 SourceLocation(), SourceLocation(),
5403 &Context->Idents.get("__builtin_va_list"),
5404 TInfo);
5405
5406 return VaListTypedefDecl;
5407}
5408
5409static TypedefDecl *
5410CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5411 // typedef struct __va_list_tag {
5412 RecordDecl *VaListTagDecl;
5413 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5414 Context->getTranslationUnitDecl(),
5415 &Context->Idents.get("__va_list_tag"));
5416 VaListTagDecl->startDefinition();
5417
5418 const size_t NumFields = 4;
5419 QualType FieldTypes[NumFields];
5420 const char *FieldNames[NumFields];
5421
5422 // unsigned gp_offset;
5423 FieldTypes[0] = Context->UnsignedIntTy;
5424 FieldNames[0] = "gp_offset";
5425
5426 // unsigned fp_offset;
5427 FieldTypes[1] = Context->UnsignedIntTy;
5428 FieldNames[1] = "fp_offset";
5429
5430 // void* overflow_arg_area;
5431 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5432 FieldNames[2] = "overflow_arg_area";
5433
5434 // void* reg_save_area;
5435 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5436 FieldNames[3] = "reg_save_area";
5437
5438 // Create fields
5439 for (unsigned i = 0; i < NumFields; ++i) {
5440 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5441 VaListTagDecl,
5442 SourceLocation(),
5443 SourceLocation(),
5444 &Context->Idents.get(FieldNames[i]),
5445 FieldTypes[i], /*TInfo=*/0,
5446 /*BitWidth=*/0,
5447 /*Mutable=*/false,
5448 ICIS_NoInit);
5449 Field->setAccess(AS_public);
5450 VaListTagDecl->addDecl(Field);
5451 }
5452 VaListTagDecl->completeDefinition();
5453 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005454 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005455
5456 // } __va_list_tag;
5457 TypedefDecl *VaListTagTypedefDecl
5458 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5459 Context->getTranslationUnitDecl(),
5460 SourceLocation(), SourceLocation(),
5461 &Context->Idents.get("__va_list_tag"),
5462 Context->getTrivialTypeSourceInfo(VaListTagType));
5463 QualType VaListTagTypedefType =
5464 Context->getTypedefType(VaListTagTypedefDecl);
5465
5466 // typedef __va_list_tag __builtin_va_list[1];
5467 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5468 QualType VaListTagArrayType
5469 = Context->getConstantArrayType(VaListTagTypedefType,
5470 Size, ArrayType::Normal,0);
5471 TypeSourceInfo *TInfo
5472 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5473 TypedefDecl *VaListTypedefDecl
5474 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5475 Context->getTranslationUnitDecl(),
5476 SourceLocation(), SourceLocation(),
5477 &Context->Idents.get("__builtin_va_list"),
5478 TInfo);
5479
5480 return VaListTypedefDecl;
5481}
5482
5483static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5484 // typedef int __builtin_va_list[4];
5485 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5486 QualType IntArrayType
5487 = Context->getConstantArrayType(Context->IntTy,
5488 Size, ArrayType::Normal, 0);
5489 TypedefDecl *VaListTypedefDecl
5490 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5491 Context->getTranslationUnitDecl(),
5492 SourceLocation(), SourceLocation(),
5493 &Context->Idents.get("__builtin_va_list"),
5494 Context->getTrivialTypeSourceInfo(IntArrayType));
5495
5496 return VaListTypedefDecl;
5497}
5498
5499static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5500 TargetInfo::BuiltinVaListKind Kind) {
5501 switch (Kind) {
5502 case TargetInfo::CharPtrBuiltinVaList:
5503 return CreateCharPtrBuiltinVaListDecl(Context);
5504 case TargetInfo::VoidPtrBuiltinVaList:
5505 return CreateVoidPtrBuiltinVaListDecl(Context);
5506 case TargetInfo::PowerABIBuiltinVaList:
5507 return CreatePowerABIBuiltinVaListDecl(Context);
5508 case TargetInfo::X86_64ABIBuiltinVaList:
5509 return CreateX86_64ABIBuiltinVaListDecl(Context);
5510 case TargetInfo::PNaClABIBuiltinVaList:
5511 return CreatePNaClABIBuiltinVaListDecl(Context);
5512 }
5513
5514 llvm_unreachable("Unhandled __builtin_va_list type kind");
5515}
5516
5517TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5518 if (!BuiltinVaListDecl)
5519 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5520
5521 return BuiltinVaListDecl;
5522}
5523
Meador Ingefb40e3f2012-07-01 15:57:25 +00005524QualType ASTContext::getVaListTagType() const {
5525 // Force the creation of VaListTagTy by building the __builtin_va_list
5526 // declaration.
5527 if (VaListTagTy.isNull())
5528 (void) getBuiltinVaListDecl();
5529
5530 return VaListTagTy;
5531}
5532
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005533void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005534 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005535 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005536
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005537 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005538}
5539
John McCall0bd6feb2009-12-02 08:04:21 +00005540/// \brief Retrieve the template name that corresponds to a non-empty
5541/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005542TemplateName
5543ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5544 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005545 unsigned size = End - Begin;
5546 assert(size > 1 && "set is not overloaded!");
5547
5548 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5549 size * sizeof(FunctionTemplateDecl*));
5550 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5551
5552 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005553 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005554 NamedDecl *D = *I;
5555 assert(isa<FunctionTemplateDecl>(D) ||
5556 (isa<UsingShadowDecl>(D) &&
5557 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5558 *Storage++ = D;
5559 }
5560
5561 return TemplateName(OT);
5562}
5563
Douglas Gregor7532dc62009-03-30 22:58:21 +00005564/// \brief Retrieve the template name that represents a qualified
5565/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005566TemplateName
5567ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5568 bool TemplateKeyword,
5569 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005570 assert(NNS && "Missing nested-name-specifier in qualified template name");
5571
Douglas Gregor789b1f62010-02-04 18:10:26 +00005572 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005573 llvm::FoldingSetNodeID ID;
5574 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5575
5576 void *InsertPos = 0;
5577 QualifiedTemplateName *QTN =
5578 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5579 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005580 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5581 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005582 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5583 }
5584
5585 return TemplateName(QTN);
5586}
5587
5588/// \brief Retrieve the template name that represents a dependent
5589/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005590TemplateName
5591ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5592 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005593 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005594 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005595
5596 llvm::FoldingSetNodeID ID;
5597 DependentTemplateName::Profile(ID, NNS, Name);
5598
5599 void *InsertPos = 0;
5600 DependentTemplateName *QTN =
5601 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5602
5603 if (QTN)
5604 return TemplateName(QTN);
5605
5606 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5607 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005608 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5609 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005610 } else {
5611 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00005612 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5613 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005614 DependentTemplateName *CheckQTN =
5615 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5616 assert(!CheckQTN && "Dependent type name canonicalization broken");
5617 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005618 }
5619
5620 DependentTemplateNames.InsertNode(QTN, InsertPos);
5621 return TemplateName(QTN);
5622}
5623
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005624/// \brief Retrieve the template name that represents a dependent
5625/// template name such as \c MetaFun::template operator+.
5626TemplateName
5627ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005628 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005629 assert((!NNS || NNS->isDependent()) &&
5630 "Nested name specifier must be dependent");
5631
5632 llvm::FoldingSetNodeID ID;
5633 DependentTemplateName::Profile(ID, NNS, Operator);
5634
5635 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005636 DependentTemplateName *QTN
5637 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005638
5639 if (QTN)
5640 return TemplateName(QTN);
5641
5642 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5643 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005644 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5645 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005646 } else {
5647 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00005648 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5649 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005650
5651 DependentTemplateName *CheckQTN
5652 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5653 assert(!CheckQTN && "Dependent template name canonicalization broken");
5654 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005655 }
5656
5657 DependentTemplateNames.InsertNode(QTN, InsertPos);
5658 return TemplateName(QTN);
5659}
5660
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005661TemplateName
John McCall14606042011-06-30 08:33:18 +00005662ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5663 TemplateName replacement) const {
5664 llvm::FoldingSetNodeID ID;
5665 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5666
5667 void *insertPos = 0;
5668 SubstTemplateTemplateParmStorage *subst
5669 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5670
5671 if (!subst) {
5672 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5673 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5674 }
5675
5676 return TemplateName(subst);
5677}
5678
5679TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005680ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5681 const TemplateArgument &ArgPack) const {
5682 ASTContext &Self = const_cast<ASTContext &>(*this);
5683 llvm::FoldingSetNodeID ID;
5684 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5685
5686 void *InsertPos = 0;
5687 SubstTemplateTemplateParmPackStorage *Subst
5688 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5689
5690 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005691 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005692 ArgPack.pack_size(),
5693 ArgPack.pack_begin());
5694 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5695 }
5696
5697 return TemplateName(Subst);
5698}
5699
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005700/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005701/// TargetInfo, produce the corresponding type. The unsigned @p Type
5702/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005703CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005704 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005705 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005706 case TargetInfo::SignedShort: return ShortTy;
5707 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5708 case TargetInfo::SignedInt: return IntTy;
5709 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5710 case TargetInfo::SignedLong: return LongTy;
5711 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5712 case TargetInfo::SignedLongLong: return LongLongTy;
5713 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5714 }
5715
David Blaikieb219cfc2011-09-23 05:06:16 +00005716 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005717}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005718
5719//===----------------------------------------------------------------------===//
5720// Type Predicates.
5721//===----------------------------------------------------------------------===//
5722
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005723/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5724/// garbage collection attribute.
5725///
John McCallae278a32011-01-12 00:34:59 +00005726Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005727 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005728 return Qualifiers::GCNone;
5729
David Blaikie4e4d0842012-03-11 07:00:24 +00005730 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005731 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5732
5733 // Default behaviour under objective-C's gc is for ObjC pointers
5734 // (or pointers to them) be treated as though they were declared
5735 // as __strong.
5736 if (GCAttrs == Qualifiers::GCNone) {
5737 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5738 return Qualifiers::Strong;
5739 else if (Ty->isPointerType())
5740 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5741 } else {
5742 // It's not valid to set GC attributes on anything that isn't a
5743 // pointer.
5744#ifndef NDEBUG
5745 QualType CT = Ty->getCanonicalTypeInternal();
5746 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5747 CT = AT->getElementType();
5748 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5749#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005750 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005751 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005752}
5753
Chris Lattner6ac46a42008-04-07 06:51:04 +00005754//===----------------------------------------------------------------------===//
5755// Type Compatibility Testing
5756//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005757
Mike Stump1eb44332009-09-09 15:08:12 +00005758/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005759/// compatible.
5760static bool areCompatVectorTypes(const VectorType *LHS,
5761 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005762 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005763 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005764 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005765}
5766
Douglas Gregor255210e2010-08-06 10:14:59 +00005767bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5768 QualType SecondVec) {
5769 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5770 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5771
5772 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5773 return true;
5774
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005775 // Treat Neon vector types and most AltiVec vector types as if they are the
5776 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005777 const VectorType *First = FirstVec->getAs<VectorType>();
5778 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005779 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005780 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005781 First->getVectorKind() != VectorType::AltiVecPixel &&
5782 First->getVectorKind() != VectorType::AltiVecBool &&
5783 Second->getVectorKind() != VectorType::AltiVecPixel &&
5784 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005785 return true;
5786
5787 return false;
5788}
5789
Steve Naroff4084c302009-07-23 01:01:38 +00005790//===----------------------------------------------------------------------===//
5791// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5792//===----------------------------------------------------------------------===//
5793
5794/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5795/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005796bool
5797ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5798 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005799 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005800 return true;
5801 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5802 E = rProto->protocol_end(); PI != E; ++PI)
5803 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5804 return true;
5805 return false;
5806}
5807
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00005808/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00005809/// return true if lhs's protocols conform to rhs's protocol; false
5810/// otherwise.
5811bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5812 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5813 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5814 return false;
5815}
5816
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00005817/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5818/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005819bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5820 QualType rhs) {
5821 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5822 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5823 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5824
5825 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5826 E = lhsQID->qual_end(); I != E; ++I) {
5827 bool match = false;
5828 ObjCProtocolDecl *lhsProto = *I;
5829 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5830 E = rhsOPT->qual_end(); J != E; ++J) {
5831 ObjCProtocolDecl *rhsProto = *J;
5832 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5833 match = true;
5834 break;
5835 }
5836 }
5837 if (!match)
5838 return false;
5839 }
5840 return true;
5841}
5842
Steve Naroff4084c302009-07-23 01:01:38 +00005843/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5844/// ObjCQualifiedIDType.
5845bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5846 bool compare) {
5847 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005848 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005849 lhs->isObjCIdType() || lhs->isObjCClassType())
5850 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005851 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005852 rhs->isObjCIdType() || rhs->isObjCClassType())
5853 return true;
5854
5855 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005856 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005857
Steve Naroff4084c302009-07-23 01:01:38 +00005858 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005859
Steve Naroff4084c302009-07-23 01:01:38 +00005860 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005861 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005862 // make sure we check the class hierarchy.
5863 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5864 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5865 E = lhsQID->qual_end(); I != E; ++I) {
5866 // when comparing an id<P> on lhs with a static type on rhs,
5867 // see if static class implements all of id's protocols, directly or
5868 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005869 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005870 return false;
5871 }
5872 }
5873 // If there are no qualifiers and no interface, we have an 'id'.
5874 return true;
5875 }
Mike Stump1eb44332009-09-09 15:08:12 +00005876 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005877 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5878 E = lhsQID->qual_end(); I != E; ++I) {
5879 ObjCProtocolDecl *lhsProto = *I;
5880 bool match = false;
5881
5882 // when comparing an id<P> on lhs with a static type on rhs,
5883 // see if static class implements all of id's protocols, directly or
5884 // through its super class and categories.
5885 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5886 E = rhsOPT->qual_end(); J != E; ++J) {
5887 ObjCProtocolDecl *rhsProto = *J;
5888 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5889 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5890 match = true;
5891 break;
5892 }
5893 }
Mike Stump1eb44332009-09-09 15:08:12 +00005894 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005895 // make sure we check the class hierarchy.
5896 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5897 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5898 E = lhsQID->qual_end(); I != E; ++I) {
5899 // when comparing an id<P> on lhs with a static type on rhs,
5900 // see if static class implements all of id's protocols, directly or
5901 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005902 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005903 match = true;
5904 break;
5905 }
5906 }
5907 }
5908 if (!match)
5909 return false;
5910 }
Mike Stump1eb44332009-09-09 15:08:12 +00005911
Steve Naroff4084c302009-07-23 01:01:38 +00005912 return true;
5913 }
Mike Stump1eb44332009-09-09 15:08:12 +00005914
Steve Naroff4084c302009-07-23 01:01:38 +00005915 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5916 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5917
Mike Stump1eb44332009-09-09 15:08:12 +00005918 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005919 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005920 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005921 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5922 E = lhsOPT->qual_end(); I != E; ++I) {
5923 ObjCProtocolDecl *lhsProto = *I;
5924 bool match = false;
5925
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005926 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005927 // see if static class implements all of id's protocols, directly or
5928 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005929 // First, lhs protocols in the qualifier list must be found, direct
5930 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005931 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5932 E = rhsQID->qual_end(); J != E; ++J) {
5933 ObjCProtocolDecl *rhsProto = *J;
5934 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5935 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5936 match = true;
5937 break;
5938 }
5939 }
5940 if (!match)
5941 return false;
5942 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005943
5944 // Static class's protocols, or its super class or category protocols
5945 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5946 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5947 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5948 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5949 // This is rather dubious but matches gcc's behavior. If lhs has
5950 // no type qualifier and its class has no static protocol(s)
5951 // assume that it is mismatch.
5952 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5953 return false;
5954 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5955 LHSInheritedProtocols.begin(),
5956 E = LHSInheritedProtocols.end(); I != E; ++I) {
5957 bool match = false;
5958 ObjCProtocolDecl *lhsProto = (*I);
5959 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5960 E = rhsQID->qual_end(); J != E; ++J) {
5961 ObjCProtocolDecl *rhsProto = *J;
5962 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5963 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5964 match = true;
5965 break;
5966 }
5967 }
5968 if (!match)
5969 return false;
5970 }
5971 }
Steve Naroff4084c302009-07-23 01:01:38 +00005972 return true;
5973 }
5974 return false;
5975}
5976
Eli Friedman3d815e72008-08-22 00:56:42 +00005977/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005978/// compatible for assignment from RHS to LHS. This handles validation of any
5979/// protocol qualifiers on the LHS or RHS.
5980///
Steve Naroff14108da2009-07-10 23:34:53 +00005981bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5982 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005983 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5984 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5985
Steve Naroffde2e22d2009-07-15 18:40:39 +00005986 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005987 if (LHS->isObjCUnqualifiedIdOrClass() ||
5988 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005989 return true;
5990
John McCallc12c5bb2010-05-15 11:32:37 +00005991 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005992 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5993 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005994 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005995
5996 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5997 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5998 QualType(RHSOPT,0));
5999
John McCallc12c5bb2010-05-15 11:32:37 +00006000 // If we have 2 user-defined types, fall into that path.
6001 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006002 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006003
Steve Naroff4084c302009-07-23 01:01:38 +00006004 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006005}
6006
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006007/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006008/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006009/// arguments in block literals. When passed as arguments, passing 'A*' where
6010/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6011/// not OK. For the return type, the opposite is not OK.
6012bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6013 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006014 const ObjCObjectPointerType *RHSOPT,
6015 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006016 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006017 return true;
6018
6019 if (LHSOPT->isObjCBuiltinType()) {
6020 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6021 }
6022
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006023 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006024 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6025 QualType(RHSOPT,0),
6026 false);
6027
6028 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6029 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6030 if (LHS && RHS) { // We have 2 user-defined types.
6031 if (LHS != RHS) {
6032 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006033 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006034 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006035 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006036 }
6037 else
6038 return true;
6039 }
6040 return false;
6041}
6042
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006043/// getIntersectionOfProtocols - This routine finds the intersection of set
6044/// of protocols inherited from two distinct objective-c pointer objects.
6045/// It is used to build composite qualifier list of the composite type of
6046/// the conditional expression involving two objective-c pointer objects.
6047static
6048void getIntersectionOfProtocols(ASTContext &Context,
6049 const ObjCObjectPointerType *LHSOPT,
6050 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006051 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006052
John McCallc12c5bb2010-05-15 11:32:37 +00006053 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6054 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6055 assert(LHS->getInterface() && "LHS must have an interface base");
6056 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006057
6058 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6059 unsigned LHSNumProtocols = LHS->getNumProtocols();
6060 if (LHSNumProtocols > 0)
6061 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6062 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006063 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006064 Context.CollectInheritedProtocols(LHS->getInterface(),
6065 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006066 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6067 LHSInheritedProtocols.end());
6068 }
6069
6070 unsigned RHSNumProtocols = RHS->getNumProtocols();
6071 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006072 ObjCProtocolDecl **RHSProtocols =
6073 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006074 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6075 if (InheritedProtocolSet.count(RHSProtocols[i]))
6076 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006077 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006078 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006079 Context.CollectInheritedProtocols(RHS->getInterface(),
6080 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006081 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6082 RHSInheritedProtocols.begin(),
6083 E = RHSInheritedProtocols.end(); I != E; ++I)
6084 if (InheritedProtocolSet.count((*I)))
6085 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006086 }
6087}
6088
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006089/// areCommonBaseCompatible - Returns common base class of the two classes if
6090/// one found. Note that this is O'2 algorithm. But it will be called as the
6091/// last type comparison in a ?-exp of ObjC pointer types before a
6092/// warning is issued. So, its invokation is extremely rare.
6093QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006094 const ObjCObjectPointerType *Lptr,
6095 const ObjCObjectPointerType *Rptr) {
6096 const ObjCObjectType *LHS = Lptr->getObjectType();
6097 const ObjCObjectType *RHS = Rptr->getObjectType();
6098 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6099 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006100 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006101 return QualType();
6102
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006103 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006104 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006105 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006106 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006107 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6108
6109 QualType Result = QualType(LHS, 0);
6110 if (!Protocols.empty())
6111 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6112 Result = getObjCObjectPointerType(Result);
6113 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006114 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006115 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006116
6117 return QualType();
6118}
6119
John McCallc12c5bb2010-05-15 11:32:37 +00006120bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6121 const ObjCObjectType *RHS) {
6122 assert(LHS->getInterface() && "LHS is not an interface type");
6123 assert(RHS->getInterface() && "RHS is not an interface type");
6124
Chris Lattner6ac46a42008-04-07 06:51:04 +00006125 // Verify that the base decls are compatible: the RHS must be a subclass of
6126 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006127 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006128 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006129
Chris Lattner6ac46a42008-04-07 06:51:04 +00006130 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6131 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006132 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006133 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006134
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006135 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6136 // more detailed analysis is required.
6137 if (RHS->getNumProtocols() == 0) {
6138 // OK, if LHS is a superclass of RHS *and*
6139 // this superclass is assignment compatible with LHS.
6140 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006141 bool IsSuperClass =
6142 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6143 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006144 // OK if conversion of LHS to SuperClass results in narrowing of types
6145 // ; i.e., SuperClass may implement at least one of the protocols
6146 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6147 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6148 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006149 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006150 // If super class has no protocols, it is not a match.
6151 if (SuperClassInheritedProtocols.empty())
6152 return false;
6153
6154 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6155 LHSPE = LHS->qual_end();
6156 LHSPI != LHSPE; LHSPI++) {
6157 bool SuperImplementsProtocol = false;
6158 ObjCProtocolDecl *LHSProto = (*LHSPI);
6159
6160 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6161 SuperClassInheritedProtocols.begin(),
6162 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6163 ObjCProtocolDecl *SuperClassProto = (*I);
6164 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6165 SuperImplementsProtocol = true;
6166 break;
6167 }
6168 }
6169 if (!SuperImplementsProtocol)
6170 return false;
6171 }
6172 return true;
6173 }
6174 return false;
6175 }
Mike Stump1eb44332009-09-09 15:08:12 +00006176
John McCallc12c5bb2010-05-15 11:32:37 +00006177 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6178 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006179 LHSPI != LHSPE; LHSPI++) {
6180 bool RHSImplementsProtocol = false;
6181
6182 // If the RHS doesn't implement the protocol on the left, the types
6183 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006184 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6185 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006186 RHSPI != RHSPE; RHSPI++) {
6187 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006188 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006189 break;
6190 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006191 }
6192 // FIXME: For better diagnostics, consider passing back the protocol name.
6193 if (!RHSImplementsProtocol)
6194 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006195 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006196 // The RHS implements all protocols listed on the LHS.
6197 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006198}
6199
Steve Naroff389bf462009-02-12 17:52:19 +00006200bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6201 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006202 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6203 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006204
Steve Naroff14108da2009-07-10 23:34:53 +00006205 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006206 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006207
6208 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6209 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006210}
6211
Douglas Gregor569c3162010-08-07 11:51:51 +00006212bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6213 return canAssignObjCInterfaces(
6214 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6215 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6216}
6217
Mike Stump1eb44332009-09-09 15:08:12 +00006218/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006219/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006220/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006221/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006222bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6223 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006224 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006225 return hasSameType(LHS, RHS);
6226
Douglas Gregor447234d2010-07-29 15:18:02 +00006227 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006228}
6229
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006230bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006231 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006232}
6233
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006234bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6235 return !mergeTypes(LHS, RHS, true).isNull();
6236}
6237
Peter Collingbourne48466752010-10-24 18:30:18 +00006238/// mergeTransparentUnionType - if T is a transparent union type and a member
6239/// of T is compatible with SubType, return the merged type, else return
6240/// QualType()
6241QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6242 bool OfBlockPointer,
6243 bool Unqualified) {
6244 if (const RecordType *UT = T->getAsUnionType()) {
6245 RecordDecl *UD = UT->getDecl();
6246 if (UD->hasAttr<TransparentUnionAttr>()) {
6247 for (RecordDecl::field_iterator it = UD->field_begin(),
6248 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006249 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006250 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6251 if (!MT.isNull())
6252 return MT;
6253 }
6254 }
6255 }
6256
6257 return QualType();
6258}
6259
6260/// mergeFunctionArgumentTypes - merge two types which appear as function
6261/// argument types
6262QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6263 bool OfBlockPointer,
6264 bool Unqualified) {
6265 // GNU extension: two types are compatible if they appear as a function
6266 // argument, one of the types is a transparent union type and the other
6267 // type is compatible with a union member
6268 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6269 Unqualified);
6270 if (!lmerge.isNull())
6271 return lmerge;
6272
6273 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6274 Unqualified);
6275 if (!rmerge.isNull())
6276 return rmerge;
6277
6278 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6279}
6280
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006281QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006282 bool OfBlockPointer,
6283 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006284 const FunctionType *lbase = lhs->getAs<FunctionType>();
6285 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006286 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6287 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006288 bool allLTypes = true;
6289 bool allRTypes = true;
6290
6291 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006292 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006293 if (OfBlockPointer) {
6294 QualType RHS = rbase->getResultType();
6295 QualType LHS = lbase->getResultType();
6296 bool UnqualifiedResult = Unqualified;
6297 if (!UnqualifiedResult)
6298 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006299 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006300 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006301 else
John McCall8cc246c2010-12-15 01:06:38 +00006302 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6303 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006304 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006305
6306 if (Unqualified)
6307 retType = retType.getUnqualifiedType();
6308
6309 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6310 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6311 if (Unqualified) {
6312 LRetType = LRetType.getUnqualifiedType();
6313 RRetType = RRetType.getUnqualifiedType();
6314 }
6315
6316 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006317 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006318 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006319 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006320
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006321 // FIXME: double check this
6322 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6323 // rbase->getRegParmAttr() != 0 &&
6324 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006325 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6326 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006327
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006328 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006329 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006330 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006331
John McCall8cc246c2010-12-15 01:06:38 +00006332 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006333 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6334 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006335 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6336 return QualType();
6337
John McCallf85e1932011-06-15 23:02:42 +00006338 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6339 return QualType();
6340
Fariborz Jahanian53c81672011-10-05 00:05:34 +00006341 // functypes which return are preferred over those that do not.
6342 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6343 allLTypes = false;
6344 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6345 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006346 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6347 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006348
John McCallf85e1932011-06-15 23:02:42 +00006349 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006350
Eli Friedman3d815e72008-08-22 00:56:42 +00006351 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006352 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6353 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006354 unsigned lproto_nargs = lproto->getNumArgs();
6355 unsigned rproto_nargs = rproto->getNumArgs();
6356
6357 // Compatible functions must have the same number of arguments
6358 if (lproto_nargs != rproto_nargs)
6359 return QualType();
6360
6361 // Variadic and non-variadic functions aren't compatible
6362 if (lproto->isVariadic() != rproto->isVariadic())
6363 return QualType();
6364
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006365 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6366 return QualType();
6367
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006368 if (LangOpts.ObjCAutoRefCount &&
6369 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6370 return QualType();
6371
Eli Friedman3d815e72008-08-22 00:56:42 +00006372 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006373 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006374 for (unsigned i = 0; i < lproto_nargs; i++) {
6375 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6376 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006377 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6378 OfBlockPointer,
6379 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006380 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006381
6382 if (Unqualified)
6383 argtype = argtype.getUnqualifiedType();
6384
Eli Friedman3d815e72008-08-22 00:56:42 +00006385 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006386 if (Unqualified) {
6387 largtype = largtype.getUnqualifiedType();
6388 rargtype = rargtype.getUnqualifiedType();
6389 }
6390
Chris Lattner61710852008-10-05 17:34:18 +00006391 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6392 allLTypes = false;
6393 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6394 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006395 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006396
Eli Friedman3d815e72008-08-22 00:56:42 +00006397 if (allLTypes) return lhs;
6398 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006399
6400 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6401 EPI.ExtInfo = einfo;
6402 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006403 }
6404
6405 if (lproto) allRTypes = false;
6406 if (rproto) allLTypes = false;
6407
Douglas Gregor72564e72009-02-26 23:50:07 +00006408 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006409 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006410 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006411 if (proto->isVariadic()) return QualType();
6412 // Check that the types are compatible with the types that
6413 // would result from default argument promotions (C99 6.7.5.3p15).
6414 // The only types actually affected are promotable integer
6415 // types and floats, which would be passed as a different
6416 // type depending on whether the prototype is visible.
6417 unsigned proto_nargs = proto->getNumArgs();
6418 for (unsigned i = 0; i < proto_nargs; ++i) {
6419 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006420
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006421 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006422 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006423 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6424 argTy = Enum->getDecl()->getIntegerType();
6425 if (argTy.isNull())
6426 return QualType();
6427 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006428
Eli Friedman3d815e72008-08-22 00:56:42 +00006429 if (argTy->isPromotableIntegerType() ||
6430 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6431 return QualType();
6432 }
6433
6434 if (allLTypes) return lhs;
6435 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006436
6437 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6438 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006439 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006440 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006441 }
6442
6443 if (allLTypes) return lhs;
6444 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006445 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006446}
6447
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006448QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006449 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006450 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006451 // C++ [expr]: If an expression initially has the type "reference to T", the
6452 // type is adjusted to "T" prior to any further analysis, the expression
6453 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006454 // expression is an lvalue unless the reference is an rvalue reference and
6455 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006456 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6457 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006458
6459 if (Unqualified) {
6460 LHS = LHS.getUnqualifiedType();
6461 RHS = RHS.getUnqualifiedType();
6462 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006463
Eli Friedman3d815e72008-08-22 00:56:42 +00006464 QualType LHSCan = getCanonicalType(LHS),
6465 RHSCan = getCanonicalType(RHS);
6466
6467 // If two types are identical, they are compatible.
6468 if (LHSCan == RHSCan)
6469 return LHS;
6470
John McCall0953e762009-09-24 19:53:00 +00006471 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006472 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6473 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006474 if (LQuals != RQuals) {
6475 // If any of these qualifiers are different, we have a type
6476 // mismatch.
6477 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006478 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6479 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006480 return QualType();
6481
6482 // Exactly one GC qualifier difference is allowed: __strong is
6483 // okay if the other type has no GC qualifier but is an Objective
6484 // C object pointer (i.e. implicitly strong by default). We fix
6485 // this by pretending that the unqualified type was actually
6486 // qualified __strong.
6487 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6488 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6489 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6490
6491 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6492 return QualType();
6493
6494 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6495 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6496 }
6497 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6498 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6499 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006500 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006501 }
6502
6503 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006504
Eli Friedman852d63b2009-06-01 01:22:52 +00006505 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6506 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006507
Chris Lattner1adb8832008-01-14 05:45:46 +00006508 // We want to consider the two function types to be the same for these
6509 // comparisons, just force one to the other.
6510 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6511 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006512
6513 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006514 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6515 LHSClass = Type::ConstantArray;
6516 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6517 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006518
John McCallc12c5bb2010-05-15 11:32:37 +00006519 // ObjCInterfaces are just specialized ObjCObjects.
6520 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6521 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6522
Nate Begeman213541a2008-04-18 23:10:10 +00006523 // Canonicalize ExtVector -> Vector.
6524 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6525 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006526
Chris Lattnera36a61f2008-04-07 05:43:21 +00006527 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006528 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006529 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006530 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006531 // Compatibility is based on the underlying type, not the promotion
6532 // type.
John McCall183700f2009-09-21 23:43:11 +00006533 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006534 QualType TINT = ETy->getDecl()->getIntegerType();
6535 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006536 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006537 }
John McCall183700f2009-09-21 23:43:11 +00006538 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006539 QualType TINT = ETy->getDecl()->getIntegerType();
6540 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006541 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006542 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006543 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006544 if (OfBlockPointer && !BlockReturnType) {
6545 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6546 return LHS;
6547 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6548 return RHS;
6549 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006550
Eli Friedman3d815e72008-08-22 00:56:42 +00006551 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006552 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006553
Steve Naroff4a746782008-01-09 22:43:08 +00006554 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006555 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006556#define TYPE(Class, Base)
6557#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006558#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006559#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6560#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6561#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006562 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006563
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006564 case Type::LValueReference:
6565 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006566 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006567 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006568
John McCallc12c5bb2010-05-15 11:32:37 +00006569 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006570 case Type::IncompleteArray:
6571 case Type::VariableArray:
6572 case Type::FunctionProto:
6573 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006574 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006575
Chris Lattner1adb8832008-01-14 05:45:46 +00006576 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006577 {
6578 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006579 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6580 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006581 if (Unqualified) {
6582 LHSPointee = LHSPointee.getUnqualifiedType();
6583 RHSPointee = RHSPointee.getUnqualifiedType();
6584 }
6585 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6586 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006587 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006588 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006589 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006590 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006591 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006592 return getPointerType(ResultType);
6593 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006594 case Type::BlockPointer:
6595 {
6596 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006597 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6598 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006599 if (Unqualified) {
6600 LHSPointee = LHSPointee.getUnqualifiedType();
6601 RHSPointee = RHSPointee.getUnqualifiedType();
6602 }
6603 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6604 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006605 if (ResultType.isNull()) return QualType();
6606 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6607 return LHS;
6608 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6609 return RHS;
6610 return getBlockPointerType(ResultType);
6611 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006612 case Type::Atomic:
6613 {
6614 // Merge two pointer types, while trying to preserve typedef info
6615 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6616 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6617 if (Unqualified) {
6618 LHSValue = LHSValue.getUnqualifiedType();
6619 RHSValue = RHSValue.getUnqualifiedType();
6620 }
6621 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6622 Unqualified);
6623 if (ResultType.isNull()) return QualType();
6624 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6625 return LHS;
6626 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6627 return RHS;
6628 return getAtomicType(ResultType);
6629 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006630 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006631 {
6632 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6633 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6634 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6635 return QualType();
6636
6637 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6638 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006639 if (Unqualified) {
6640 LHSElem = LHSElem.getUnqualifiedType();
6641 RHSElem = RHSElem.getUnqualifiedType();
6642 }
6643
6644 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006645 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006646 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6647 return LHS;
6648 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6649 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006650 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6651 ArrayType::ArraySizeModifier(), 0);
6652 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6653 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006654 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6655 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006656 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6657 return LHS;
6658 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6659 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006660 if (LVAT) {
6661 // FIXME: This isn't correct! But tricky to implement because
6662 // the array's size has to be the size of LHS, but the type
6663 // has to be different.
6664 return LHS;
6665 }
6666 if (RVAT) {
6667 // FIXME: This isn't correct! But tricky to implement because
6668 // the array's size has to be the size of RHS, but the type
6669 // has to be different.
6670 return RHS;
6671 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006672 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6673 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006674 return getIncompleteArrayType(ResultType,
6675 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006676 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006677 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006678 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006679 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006680 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006681 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006682 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006683 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006684 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006685 case Type::Complex:
6686 // Distinct complex types are incompatible.
6687 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006688 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006689 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006690 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6691 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006692 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006693 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006694 case Type::ObjCObject: {
6695 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006696 // FIXME: This should be type compatibility, e.g. whether
6697 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006698 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6699 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6700 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006701 return LHS;
6702
Eli Friedman3d815e72008-08-22 00:56:42 +00006703 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006704 }
Steve Naroff14108da2009-07-10 23:34:53 +00006705 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006706 if (OfBlockPointer) {
6707 if (canAssignObjCInterfacesInBlockPointer(
6708 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006709 RHS->getAs<ObjCObjectPointerType>(),
6710 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006711 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006712 return QualType();
6713 }
John McCall183700f2009-09-21 23:43:11 +00006714 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6715 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006716 return LHS;
6717
Steve Naroffbc76dd02008-12-10 22:14:21 +00006718 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006719 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006720 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006721
David Blaikie7530c032012-01-17 06:56:22 +00006722 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006723}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006724
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006725bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6726 const FunctionProtoType *FromFunctionType,
6727 const FunctionProtoType *ToFunctionType) {
6728 if (FromFunctionType->hasAnyConsumedArgs() !=
6729 ToFunctionType->hasAnyConsumedArgs())
6730 return false;
6731 FunctionProtoType::ExtProtoInfo FromEPI =
6732 FromFunctionType->getExtProtoInfo();
6733 FunctionProtoType::ExtProtoInfo ToEPI =
6734 ToFunctionType->getExtProtoInfo();
6735 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6736 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6737 ArgIdx != NumArgs; ++ArgIdx) {
6738 if (FromEPI.ConsumedArguments[ArgIdx] !=
6739 ToEPI.ConsumedArguments[ArgIdx])
6740 return false;
6741 }
6742 return true;
6743}
6744
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006745/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6746/// 'RHS' attributes and returns the merged version; including for function
6747/// return types.
6748QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6749 QualType LHSCan = getCanonicalType(LHS),
6750 RHSCan = getCanonicalType(RHS);
6751 // If two types are identical, they are compatible.
6752 if (LHSCan == RHSCan)
6753 return LHS;
6754 if (RHSCan->isFunctionType()) {
6755 if (!LHSCan->isFunctionType())
6756 return QualType();
6757 QualType OldReturnType =
6758 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6759 QualType NewReturnType =
6760 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6761 QualType ResReturnType =
6762 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6763 if (ResReturnType.isNull())
6764 return QualType();
6765 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6766 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6767 // In either case, use OldReturnType to build the new function type.
6768 const FunctionType *F = LHS->getAs<FunctionType>();
6769 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006770 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6771 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006772 QualType ResultType
6773 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006774 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006775 return ResultType;
6776 }
6777 }
6778 return QualType();
6779 }
6780
6781 // If the qualifiers are different, the types can still be merged.
6782 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6783 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6784 if (LQuals != RQuals) {
6785 // If any of these qualifiers are different, we have a type mismatch.
6786 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6787 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6788 return QualType();
6789
6790 // Exactly one GC qualifier difference is allowed: __strong is
6791 // okay if the other type has no GC qualifier but is an Objective
6792 // C object pointer (i.e. implicitly strong by default). We fix
6793 // this by pretending that the unqualified type was actually
6794 // qualified __strong.
6795 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6796 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6797 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6798
6799 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6800 return QualType();
6801
6802 if (GC_L == Qualifiers::Strong)
6803 return LHS;
6804 if (GC_R == Qualifiers::Strong)
6805 return RHS;
6806 return QualType();
6807 }
6808
6809 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6810 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6811 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6812 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6813 if (ResQT == LHSBaseQT)
6814 return LHS;
6815 if (ResQT == RHSBaseQT)
6816 return RHS;
6817 }
6818 return QualType();
6819}
6820
Chris Lattner5426bf62008-04-07 07:01:58 +00006821//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006822// Integer Predicates
6823//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006824
Jay Foad4ba2a172011-01-12 09:06:06 +00006825unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006826 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006827 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006828 if (T->isBooleanType())
6829 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006830 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006831 return (unsigned)getTypeSize(T);
6832}
6833
Abramo Bagnara762f1592012-09-09 10:21:24 +00006834QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00006835 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006836
6837 // Turn <4 x signed int> -> <4 x unsigned int>
6838 if (const VectorType *VTy = T->getAs<VectorType>())
6839 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006840 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006841
6842 // For enums, we return the unsigned version of the base type.
6843 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006844 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006845
6846 const BuiltinType *BTy = T->getAs<BuiltinType>();
6847 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006848 switch (BTy->getKind()) {
6849 case BuiltinType::Char_S:
6850 case BuiltinType::SChar:
6851 return UnsignedCharTy;
6852 case BuiltinType::Short:
6853 return UnsignedShortTy;
6854 case BuiltinType::Int:
6855 return UnsignedIntTy;
6856 case BuiltinType::Long:
6857 return UnsignedLongTy;
6858 case BuiltinType::LongLong:
6859 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006860 case BuiltinType::Int128:
6861 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006862 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006863 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006864 }
6865}
6866
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006867ASTMutationListener::~ASTMutationListener() { }
6868
Chris Lattner86df27b2009-06-14 00:45:47 +00006869
6870//===----------------------------------------------------------------------===//
6871// Builtin Type Computation
6872//===----------------------------------------------------------------------===//
6873
6874/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006875/// pointer over the consumed characters. This returns the resultant type. If
6876/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6877/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6878/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006879///
6880/// RequiresICE is filled in on return to indicate whether the value is required
6881/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006882static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006883 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006884 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006885 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006886 // Modifiers.
6887 int HowLong = 0;
6888 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006889 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006890
Chris Lattner33daae62010-10-01 22:42:38 +00006891 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006892 bool Done = false;
6893 while (!Done) {
6894 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006895 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006896 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006897 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006898 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006899 case 'S':
6900 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6901 assert(!Signed && "Can't use 'S' modifier multiple times!");
6902 Signed = true;
6903 break;
6904 case 'U':
6905 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6906 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6907 Unsigned = true;
6908 break;
6909 case 'L':
6910 assert(HowLong <= 2 && "Can't have LLLL modifier");
6911 ++HowLong;
6912 break;
6913 }
6914 }
6915
6916 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006917
Chris Lattner86df27b2009-06-14 00:45:47 +00006918 // Read the base type.
6919 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006920 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006921 case 'v':
6922 assert(HowLong == 0 && !Signed && !Unsigned &&
6923 "Bad modifiers used with 'v'!");
6924 Type = Context.VoidTy;
6925 break;
6926 case 'f':
6927 assert(HowLong == 0 && !Signed && !Unsigned &&
6928 "Bad modifiers used with 'f'!");
6929 Type = Context.FloatTy;
6930 break;
6931 case 'd':
6932 assert(HowLong < 2 && !Signed && !Unsigned &&
6933 "Bad modifiers used with 'd'!");
6934 if (HowLong)
6935 Type = Context.LongDoubleTy;
6936 else
6937 Type = Context.DoubleTy;
6938 break;
6939 case 's':
6940 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6941 if (Unsigned)
6942 Type = Context.UnsignedShortTy;
6943 else
6944 Type = Context.ShortTy;
6945 break;
6946 case 'i':
6947 if (HowLong == 3)
6948 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6949 else if (HowLong == 2)
6950 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6951 else if (HowLong == 1)
6952 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6953 else
6954 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6955 break;
6956 case 'c':
6957 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6958 if (Signed)
6959 Type = Context.SignedCharTy;
6960 else if (Unsigned)
6961 Type = Context.UnsignedCharTy;
6962 else
6963 Type = Context.CharTy;
6964 break;
6965 case 'b': // boolean
6966 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6967 Type = Context.BoolTy;
6968 break;
6969 case 'z': // size_t.
6970 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6971 Type = Context.getSizeType();
6972 break;
6973 case 'F':
6974 Type = Context.getCFConstantStringType();
6975 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006976 case 'G':
6977 Type = Context.getObjCIdType();
6978 break;
6979 case 'H':
6980 Type = Context.getObjCSelType();
6981 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006982 case 'a':
6983 Type = Context.getBuiltinVaListType();
6984 assert(!Type.isNull() && "builtin va list type not initialized!");
6985 break;
6986 case 'A':
6987 // This is a "reference" to a va_list; however, what exactly
6988 // this means depends on how va_list is defined. There are two
6989 // different kinds of va_list: ones passed by value, and ones
6990 // passed by reference. An example of a by-value va_list is
6991 // x86, where va_list is a char*. An example of by-ref va_list
6992 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6993 // we want this argument to be a char*&; for x86-64, we want
6994 // it to be a __va_list_tag*.
6995 Type = Context.getBuiltinVaListType();
6996 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006997 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006998 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006999 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007000 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007001 break;
7002 case 'V': {
7003 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007004 unsigned NumElements = strtoul(Str, &End, 10);
7005 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007006 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007007
Chris Lattner14e0e742010-10-01 22:53:11 +00007008 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7009 RequiresICE, false);
7010 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007011
7012 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007013 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007014 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007015 break;
7016 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007017 case 'E': {
7018 char *End;
7019
7020 unsigned NumElements = strtoul(Str, &End, 10);
7021 assert(End != Str && "Missing vector size");
7022
7023 Str = End;
7024
7025 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7026 false);
7027 Type = Context.getExtVectorType(ElementType, NumElements);
7028 break;
7029 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007030 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007031 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7032 false);
7033 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007034 Type = Context.getComplexType(ElementType);
7035 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007036 }
7037 case 'Y' : {
7038 Type = Context.getPointerDiffType();
7039 break;
7040 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007041 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007042 Type = Context.getFILEType();
7043 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007044 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007045 return QualType();
7046 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007047 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007048 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007049 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007050 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007051 else
7052 Type = Context.getjmp_bufType();
7053
Mike Stumpfd612db2009-07-28 23:47:15 +00007054 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007055 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007056 return QualType();
7057 }
7058 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007059 case 'K':
7060 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7061 Type = Context.getucontext_tType();
7062
7063 if (Type.isNull()) {
7064 Error = ASTContext::GE_Missing_ucontext;
7065 return QualType();
7066 }
7067 break;
Mike Stump782fa302009-07-28 02:25:19 +00007068 }
Mike Stump1eb44332009-09-09 15:08:12 +00007069
Chris Lattner33daae62010-10-01 22:42:38 +00007070 // If there are modifiers and if we're allowed to parse them, go for it.
7071 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007072 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007073 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007074 default: Done = true; --Str; break;
7075 case '*':
7076 case '&': {
7077 // Both pointers and references can have their pointee types
7078 // qualified with an address space.
7079 char *End;
7080 unsigned AddrSpace = strtoul(Str, &End, 10);
7081 if (End != Str && AddrSpace != 0) {
7082 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7083 Str = End;
7084 }
7085 if (c == '*')
7086 Type = Context.getPointerType(Type);
7087 else
7088 Type = Context.getLValueReferenceType(Type);
7089 break;
7090 }
7091 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7092 case 'C':
7093 Type = Type.withConst();
7094 break;
7095 case 'D':
7096 Type = Context.getVolatileType(Type);
7097 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007098 case 'R':
7099 Type = Type.withRestrict();
7100 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007101 }
7102 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007103
Chris Lattner14e0e742010-10-01 22:53:11 +00007104 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007105 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007106
Chris Lattner86df27b2009-06-14 00:45:47 +00007107 return Type;
7108}
7109
7110/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007111QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007112 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007113 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007114 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007115
Chris Lattner5f9e2722011-07-23 10:55:15 +00007116 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007117
Chris Lattner14e0e742010-10-01 22:53:11 +00007118 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007119 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007120 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7121 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007122 if (Error != GE_None)
7123 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007124
7125 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7126
Chris Lattner86df27b2009-06-14 00:45:47 +00007127 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007128 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007129 if (Error != GE_None)
7130 return QualType();
7131
Chris Lattner14e0e742010-10-01 22:53:11 +00007132 // If this argument is required to be an IntegerConstantExpression and the
7133 // caller cares, fill in the bitmask we return.
7134 if (RequiresICE && IntegerConstantArgs)
7135 *IntegerConstantArgs |= 1 << ArgTypes.size();
7136
Chris Lattner86df27b2009-06-14 00:45:47 +00007137 // Do array -> pointer decay. The builtin should use the decayed type.
7138 if (Ty->isArrayType())
7139 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007140
Chris Lattner86df27b2009-06-14 00:45:47 +00007141 ArgTypes.push_back(Ty);
7142 }
7143
7144 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7145 "'.' should only occur at end of builtin type list!");
7146
John McCall00ccbef2010-12-21 00:44:39 +00007147 FunctionType::ExtInfo EI;
7148 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7149
7150 bool Variadic = (TypeStr[0] == '.');
7151
7152 // We really shouldn't be making a no-proto type here, especially in C++.
7153 if (ArgTypes.empty() && Variadic)
7154 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007155
John McCalle23cf432010-12-14 08:05:40 +00007156 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007157 EPI.ExtInfo = EI;
7158 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007159
7160 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007161}
Eli Friedmana95d7572009-08-19 07:44:53 +00007162
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007163GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7164 GVALinkage External = GVA_StrongExternal;
7165
7166 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007167 switch (L) {
7168 case NoLinkage:
7169 case InternalLinkage:
7170 case UniqueExternalLinkage:
7171 return GVA_Internal;
7172
7173 case ExternalLinkage:
7174 switch (FD->getTemplateSpecializationKind()) {
7175 case TSK_Undeclared:
7176 case TSK_ExplicitSpecialization:
7177 External = GVA_StrongExternal;
7178 break;
7179
7180 case TSK_ExplicitInstantiationDefinition:
7181 return GVA_ExplicitTemplateInstantiation;
7182
7183 case TSK_ExplicitInstantiationDeclaration:
7184 case TSK_ImplicitInstantiation:
7185 External = GVA_TemplateInstantiation;
7186 break;
7187 }
7188 }
7189
7190 if (!FD->isInlined())
7191 return External;
7192
David Blaikie4e4d0842012-03-11 07:00:24 +00007193 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007194 // GNU or C99 inline semantics. Determine whether this symbol should be
7195 // externally visible.
7196 if (FD->isInlineDefinitionExternallyVisible())
7197 return External;
7198
7199 // C99 inline semantics, where the symbol is not externally visible.
7200 return GVA_C99Inline;
7201 }
7202
7203 // C++0x [temp.explicit]p9:
7204 // [ Note: The intent is that an inline function that is the subject of
7205 // an explicit instantiation declaration will still be implicitly
7206 // instantiated when used so that the body can be considered for
7207 // inlining, but that no out-of-line copy of the inline function would be
7208 // generated in the translation unit. -- end note ]
7209 if (FD->getTemplateSpecializationKind()
7210 == TSK_ExplicitInstantiationDeclaration)
7211 return GVA_C99Inline;
7212
7213 return GVA_CXXInline;
7214}
7215
7216GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7217 // If this is a static data member, compute the kind of template
7218 // specialization. Otherwise, this variable is not part of a
7219 // template.
7220 TemplateSpecializationKind TSK = TSK_Undeclared;
7221 if (VD->isStaticDataMember())
7222 TSK = VD->getTemplateSpecializationKind();
7223
7224 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00007225 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007226 VD->getType()->getLinkage() == UniqueExternalLinkage)
7227 L = UniqueExternalLinkage;
7228
7229 switch (L) {
7230 case NoLinkage:
7231 case InternalLinkage:
7232 case UniqueExternalLinkage:
7233 return GVA_Internal;
7234
7235 case ExternalLinkage:
7236 switch (TSK) {
7237 case TSK_Undeclared:
7238 case TSK_ExplicitSpecialization:
7239 return GVA_StrongExternal;
7240
7241 case TSK_ExplicitInstantiationDeclaration:
7242 llvm_unreachable("Variable should not be instantiated");
7243 // Fall through to treat this like any other instantiation.
7244
7245 case TSK_ExplicitInstantiationDefinition:
7246 return GVA_ExplicitTemplateInstantiation;
7247
7248 case TSK_ImplicitInstantiation:
7249 return GVA_TemplateInstantiation;
7250 }
7251 }
7252
David Blaikie7530c032012-01-17 06:56:22 +00007253 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007254}
7255
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007256bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007257 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7258 if (!VD->isFileVarDecl())
7259 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007260 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007261 return false;
7262
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007263 // Weak references don't produce any output by themselves.
7264 if (D->hasAttr<WeakRefAttr>())
7265 return false;
7266
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007267 // Aliases and used decls are required.
7268 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7269 return true;
7270
7271 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7272 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007273 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007274 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007275
7276 // Constructors and destructors are required.
7277 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7278 return true;
7279
7280 // The key function for a class is required.
7281 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7282 const CXXRecordDecl *RD = MD->getParent();
7283 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7284 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7285 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7286 return true;
7287 }
7288 }
7289
7290 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7291
7292 // static, static inline, always_inline, and extern inline functions can
7293 // always be deferred. Normal inline functions can be deferred in C99/C++.
7294 // Implicit template instantiations can also be deferred in C++.
7295 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007296 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007297 return false;
7298 return true;
7299 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007300
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007301 const VarDecl *VD = cast<VarDecl>(D);
7302 assert(VD->isFileVarDecl() && "Expected file scoped var");
7303
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007304 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7305 return false;
7306
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007307 // Structs that have non-trivial constructors or destructors are required.
7308
7309 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00007310 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007311 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7312 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00007313 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7314 RD->hasTrivialCopyConstructor() &&
7315 RD->hasTrivialMoveConstructor() &&
7316 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007317 return true;
7318 }
7319 }
7320
7321 GVALinkage L = GetGVALinkageForVariable(VD);
7322 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7323 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7324 return false;
7325 }
7326
7327 return true;
7328}
Charles Davis071cc7d2010-08-16 03:33:14 +00007329
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007330CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007331 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007332 return ABI->getDefaultMethodCallConv(isVariadic);
7333}
7334
7335CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7336 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7337 return CC_Default;
7338 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007339}
7340
Jay Foad4ba2a172011-01-12 09:06:06 +00007341bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007342 // Pass through to the C++ ABI object
7343 return ABI->isNearlyEmpty(RD);
7344}
7345
Peter Collingbourne14110472011-01-13 18:57:25 +00007346MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007347 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007348 case CXXABI_ARM:
7349 case CXXABI_Itanium:
7350 return createItaniumMangleContext(*this, getDiagnostics());
7351 case CXXABI_Microsoft:
7352 return createMicrosoftMangleContext(*this, getDiagnostics());
7353 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007354 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007355}
7356
Charles Davis071cc7d2010-08-16 03:33:14 +00007357CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007358
7359size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007360 return ASTRecordLayouts.getMemorySize()
7361 + llvm::capacity_in_bytes(ObjCLayouts)
7362 + llvm::capacity_in_bytes(KeyFunctions)
7363 + llvm::capacity_in_bytes(ObjCImpls)
7364 + llvm::capacity_in_bytes(BlockVarCopyInits)
7365 + llvm::capacity_in_bytes(DeclAttrs)
7366 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7367 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7368 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7369 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7370 + llvm::capacity_in_bytes(OverriddenMethods)
7371 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007372 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007373 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007374}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007375
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007376unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7377 CXXRecordDecl *Lambda = CallOperator->getParent();
7378 return LambdaMangleContexts[Lambda->getDeclContext()]
7379 .getManglingNumber(CallOperator);
7380}
7381
7382
Ted Kremenekd211cb72011-10-06 05:00:56 +00007383void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7384 ParamIndices[D] = index;
7385}
7386
7387unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7388 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7389 assert(I != ParamIndices.end() &&
7390 "ParmIndices lacks entry set by ParmVarDecl");
7391 return I->second;
7392}