blob: 94bb9a925955e1daeadec5a22a22b98cb0b3e9bc [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 Gribenko19523542012-09-29 11:40:46 +0000358comments::FullComment *ASTContext::getCommentForDecl(
359 const Decl *D,
360 const Preprocessor *PP) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000361 D = adjustDeclToTemplate(D);
362 const Decl *Canonical = D->getCanonicalDecl();
363 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
364 ParsedComments.find(Canonical);
365 if (Pos != ParsedComments.end())
366 return Pos->second;
367
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000368 const Decl *OriginalDecl;
369 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000370 if (!RC)
371 return NULL;
372
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000373 // If the RawComment was attached to other redeclaration of this Decl, we
374 // should parse the comment in context of that other Decl. This is important
375 // because comments can contain references to parameter names which can be
376 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000377 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000378 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000379
Dmitri Gribenko19523542012-09-29 11:40:46 +0000380 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000381 ParsedComments[Canonical] = FC;
382 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000383}
384
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000385void
386ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
387 TemplateTemplateParmDecl *Parm) {
388 ID.AddInteger(Parm->getDepth());
389 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000390 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000391
392 TemplateParameterList *Params = Parm->getTemplateParameters();
393 ID.AddInteger(Params->size());
394 for (TemplateParameterList::const_iterator P = Params->begin(),
395 PEnd = Params->end();
396 P != PEnd; ++P) {
397 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
398 ID.AddInteger(0);
399 ID.AddBoolean(TTP->isParameterPack());
400 continue;
401 }
402
403 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
404 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000405 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000406 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000407 if (NTTP->isExpandedParameterPack()) {
408 ID.AddBoolean(true);
409 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000410 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
411 QualType T = NTTP->getExpansionType(I);
412 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
413 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000414 } else
415 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000416 continue;
417 }
418
419 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
420 ID.AddInteger(2);
421 Profile(ID, TTP);
422 }
423}
424
425TemplateTemplateParmDecl *
426ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000427 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000428 // Check if we already have a canonical template template parameter.
429 llvm::FoldingSetNodeID ID;
430 CanonicalTemplateTemplateParm::Profile(ID, TTP);
431 void *InsertPos = 0;
432 CanonicalTemplateTemplateParm *Canonical
433 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
434 if (Canonical)
435 return Canonical->getParam();
436
437 // Build a canonical template parameter list.
438 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000439 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000440 CanonParams.reserve(Params->size());
441 for (TemplateParameterList::const_iterator P = Params->begin(),
442 PEnd = Params->end();
443 P != PEnd; ++P) {
444 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
445 CanonParams.push_back(
446 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000447 SourceLocation(),
448 SourceLocation(),
449 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000450 TTP->getIndex(), 0, false,
451 TTP->isParameterPack()));
452 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000453 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
454 QualType T = getCanonicalType(NTTP->getType());
455 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
456 NonTypeTemplateParmDecl *Param;
457 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000458 SmallVector<QualType, 2> ExpandedTypes;
459 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000460 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
461 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
462 ExpandedTInfos.push_back(
463 getTrivialTypeSourceInfo(ExpandedTypes.back()));
464 }
465
466 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000467 SourceLocation(),
468 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000469 NTTP->getDepth(),
470 NTTP->getPosition(), 0,
471 T,
472 TInfo,
473 ExpandedTypes.data(),
474 ExpandedTypes.size(),
475 ExpandedTInfos.data());
476 } else {
477 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000478 SourceLocation(),
479 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000480 NTTP->getDepth(),
481 NTTP->getPosition(), 0,
482 T,
483 NTTP->isParameterPack(),
484 TInfo);
485 }
486 CanonParams.push_back(Param);
487
488 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000489 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
490 cast<TemplateTemplateParmDecl>(*P)));
491 }
492
493 TemplateTemplateParmDecl *CanonTTP
494 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
495 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000496 TTP->getPosition(),
497 TTP->isParameterPack(),
498 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000499 TemplateParameterList::Create(*this, SourceLocation(),
500 SourceLocation(),
501 CanonParams.data(),
502 CanonParams.size(),
503 SourceLocation()));
504
505 // Get the new insert position for the node we care about.
506 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
507 assert(Canonical == 0 && "Shouldn't be in the map!");
508 (void)Canonical;
509
510 // Create the canonical template template parameter entry.
511 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
512 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
513 return CanonTTP;
514}
515
Charles Davis071cc7d2010-08-16 03:33:14 +0000516CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000517 if (!LangOpts.CPlusPlus) return 0;
518
Charles Davis20cf7172010-08-19 02:18:14 +0000519 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000520 case CXXABI_ARM:
521 return CreateARMCXXABI(*this);
522 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000523 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000524 case CXXABI_Microsoft:
525 return CreateMicrosoftCXXABI(*this);
526 }
David Blaikie7530c032012-01-17 06:56:22 +0000527 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000528}
529
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000530static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000531 const LangOptions &LOpts) {
532 if (LOpts.FakeAddressSpaceMap) {
533 // The fake address space map must have a distinct entry for each
534 // language-specific address space.
535 static const unsigned FakeAddrSpaceMap[] = {
536 1, // opencl_global
537 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000538 3, // opencl_constant
539 4, // cuda_device
540 5, // cuda_constant
541 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000542 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000543 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000544 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000545 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000546 }
547}
548
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000549ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000550 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000551 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000552 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000553 unsigned size_reserve,
554 bool DelayInitialization)
555 : FunctionProtoTypes(this_()),
556 TemplateSpecializationTypes(this_()),
557 DependentTemplateSpecializationTypes(this_()),
558 SubstTemplateTemplateParmPacks(this_()),
559 GlobalNestedNameSpecifier(0),
560 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000561 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000562 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000563 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000564 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000565 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000566 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
567 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
568 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000569 NullTypeSourceInfo(QualType()),
570 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000571 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000572 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000573 Idents(idents), Selectors(sels),
574 BuiltinInfo(builtins),
575 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000576 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000577 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000578 CommentCommandTraits(BumpAlloc),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000579 LastSDM(0, 0),
580 UniqueBlockByRefTypeID(0)
581{
Mike Stump1eb44332009-09-09 15:08:12 +0000582 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000583 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000584
585 if (!DelayInitialization) {
586 assert(t && "No target supplied for ASTContext initialization");
587 InitBuiltinTypes(*t);
588 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000589}
590
Reid Spencer5f016e22007-07-11 17:01:13 +0000591ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000592 // Release the DenseMaps associated with DeclContext objects.
593 // FIXME: Is this the ideal solution?
594 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000595
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000596 // Call all of the deallocation functions.
597 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
598 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000599
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000600 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000601 // because they can contain DenseMaps.
602 for (llvm::DenseMap<const ObjCContainerDecl*,
603 const ASTRecordLayout*>::iterator
604 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
605 // Increment in loop to prevent using deallocated memory.
606 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
607 R->Destroy(*this);
608
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000609 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
610 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
611 // Increment in loop to prevent using deallocated memory.
612 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
613 R->Destroy(*this);
614 }
Douglas Gregor63200642010-08-30 16:49:28 +0000615
616 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
617 AEnd = DeclAttrs.end();
618 A != AEnd; ++A)
619 A->second->~AttrVec();
620}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000621
Douglas Gregor00545312010-05-23 18:26:36 +0000622void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
623 Deallocations.push_back(std::make_pair(Callback, Data));
624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000627ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000628 ExternalSource.reset(Source.take());
629}
630
Reid Spencer5f016e22007-07-11 17:01:13 +0000631void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000632 llvm::errs() << "\n*** AST Context Stats:\n";
633 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000634
Douglas Gregordbe833d2009-05-26 14:40:08 +0000635 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000636#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000637#define ABSTRACT_TYPE(Name, Parent)
638#include "clang/AST/TypeNodes.def"
639 0 // Extra
640 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000641
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
643 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000644 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 }
646
Douglas Gregordbe833d2009-05-26 14:40:08 +0000647 unsigned Idx = 0;
648 unsigned TotalBytes = 0;
649#define TYPE(Name, Parent) \
650 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000651 llvm::errs() << " " << counts[Idx] << " " << #Name \
652 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000653 TotalBytes += counts[Idx] * sizeof(Name##Type); \
654 ++Idx;
655#define ABSTRACT_TYPE(Name, Parent)
656#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chandler Carruthcd92a652011-07-04 05:32:14 +0000658 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
659
Douglas Gregor4923aa22010-07-02 20:37:36 +0000660 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000661 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
662 << NumImplicitDefaultConstructors
663 << " implicit default constructors created\n";
664 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
665 << NumImplicitCopyConstructors
666 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000667 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000668 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
669 << NumImplicitMoveConstructors
670 << " implicit move constructors created\n";
671 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
672 << NumImplicitCopyAssignmentOperators
673 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000674 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000675 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
676 << NumImplicitMoveAssignmentOperators
677 << " implicit move assignment operators created\n";
678 llvm::errs() << NumImplicitDestructorsDeclared << "/"
679 << NumImplicitDestructors
680 << " implicit destructors created\n";
681
Douglas Gregor2cf26342009-04-09 22:27:44 +0000682 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000683 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000684 ExternalSource->PrintStats();
685 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000686
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000687 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000688}
689
Douglas Gregor772eeae2011-08-12 06:49:56 +0000690TypedefDecl *ASTContext::getInt128Decl() const {
691 if (!Int128Decl) {
692 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
693 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
694 getTranslationUnitDecl(),
695 SourceLocation(),
696 SourceLocation(),
697 &Idents.get("__int128_t"),
698 TInfo);
699 }
700
701 return Int128Decl;
702}
703
704TypedefDecl *ASTContext::getUInt128Decl() const {
705 if (!UInt128Decl) {
706 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
707 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
708 getTranslationUnitDecl(),
709 SourceLocation(),
710 SourceLocation(),
711 &Idents.get("__uint128_t"),
712 TInfo);
713 }
714
715 return UInt128Decl;
716}
Reid Spencer5f016e22007-07-11 17:01:13 +0000717
John McCalle27ec8a2009-10-23 23:03:21 +0000718void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000719 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000720 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000721 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000722}
723
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000724void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
725 assert((!this->Target || this->Target == &Target) &&
726 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000729 this->Target = &Target;
730
731 ABI.reset(createCXXABI(Target));
732 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
733
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 // C99 6.2.5p19.
735 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 // C99 6.2.5p2.
738 InitBuiltinType(BoolTy, BuiltinType::Bool);
739 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000740 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 InitBuiltinType(CharTy, BuiltinType::Char_S);
742 else
743 InitBuiltinType(CharTy, BuiltinType::Char_U);
744 // C99 6.2.5p4.
745 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
746 InitBuiltinType(ShortTy, BuiltinType::Short);
747 InitBuiltinType(IntTy, BuiltinType::Int);
748 InitBuiltinType(LongTy, BuiltinType::Long);
749 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 // C99 6.2.5p6.
752 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
753 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
754 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
755 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
756 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 // C99 6.2.5p10.
759 InitBuiltinType(FloatTy, BuiltinType::Float);
760 InitBuiltinType(DoubleTy, BuiltinType::Double);
761 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000762
Chris Lattner2df9ced2009-04-30 02:43:43 +0000763 // GNU extension, 128-bit integers.
764 InitBuiltinType(Int128Ty, BuiltinType::Int128);
765 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
766
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000767 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000768 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000769 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
770 else // -fshort-wchar makes wchar_t be unsigned.
771 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000772 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000773 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000774
James Molloy392da482012-05-04 10:55:22 +0000775 WIntTy = getFromTargetType(Target.getWIntType());
776
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000777 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
778 InitBuiltinType(Char16Ty, BuiltinType::Char16);
779 else // C99
780 Char16Ty = getFromTargetType(Target.getChar16Type());
781
782 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
783 InitBuiltinType(Char32Ty, BuiltinType::Char32);
784 else // C99
785 Char32Ty = getFromTargetType(Target.getChar32Type());
786
Douglas Gregor898574e2008-12-05 23:32:09 +0000787 // Placeholder type for type-dependent expressions whose type is
788 // completely unknown. No code should ever check a type against
789 // DependentTy and users should never see it; however, it is here to
790 // help diagnose failures to properly check for type-dependent
791 // expressions.
792 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000793
John McCall2a984ca2010-10-12 00:20:44 +0000794 // Placeholder type for functions.
795 InitBuiltinType(OverloadTy, BuiltinType::Overload);
796
John McCall864c0412011-04-26 20:42:42 +0000797 // Placeholder type for bound members.
798 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
799
John McCall3c3b7f92011-10-25 17:37:35 +0000800 // Placeholder type for pseudo-objects.
801 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
802
John McCall1de4d4e2011-04-07 08:22:57 +0000803 // "any" type; useful for debugger-like clients.
804 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
805
John McCall0ddaeb92011-10-17 18:09:15 +0000806 // Placeholder type for unbridged ARC casts.
807 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
808
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000809 // Placeholder type for builtin functions.
810 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
811
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 // C99 6.2.5p11.
813 FloatComplexTy = getComplexType(FloatTy);
814 DoubleComplexTy = getComplexType(DoubleTy);
815 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000817 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000818 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
819 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000820 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000821
822 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000823 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
824 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000825
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000826 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000828 // void * type
829 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000830
831 // nullptr type (C++0x 2.14.7)
832 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000833
834 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
835 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000836
837 // Builtin type used to help define __builtin_va_list.
838 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000839}
840
David Blaikied6471f72011-09-25 23:23:43 +0000841DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000842 return SourceMgr.getDiagnostics();
843}
844
Douglas Gregor63200642010-08-30 16:49:28 +0000845AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
846 AttrVec *&Result = DeclAttrs[D];
847 if (!Result) {
848 void *Mem = Allocate(sizeof(AttrVec));
849 Result = new (Mem) AttrVec;
850 }
851
852 return *Result;
853}
854
855/// \brief Erase the attributes corresponding to the given declaration.
856void ASTContext::eraseDeclAttrs(const Decl *D) {
857 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
858 if (Pos != DeclAttrs.end()) {
859 Pos->second->~AttrVec();
860 DeclAttrs.erase(Pos);
861 }
862}
863
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000864MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000865ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000866 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000867 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000868 = InstantiatedFromStaticDataMember.find(Var);
869 if (Pos == InstantiatedFromStaticDataMember.end())
870 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Douglas Gregor7caa6822009-07-24 20:34:43 +0000872 return Pos->second;
873}
874
Mike Stump1eb44332009-09-09 15:08:12 +0000875void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000876ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000877 TemplateSpecializationKind TSK,
878 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000879 assert(Inst->isStaticDataMember() && "Not a static data member");
880 assert(Tmpl->isStaticDataMember() && "Not a static data member");
881 assert(!InstantiatedFromStaticDataMember[Inst] &&
882 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000883 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000884 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000885}
886
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000887FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
888 const FunctionDecl *FD){
889 assert(FD && "Specialization is 0");
890 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000891 = ClassScopeSpecializationPattern.find(FD);
892 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000893 return 0;
894
895 return Pos->second;
896}
897
898void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
899 FunctionDecl *Pattern) {
900 assert(FD && "Specialization is 0");
901 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000902 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000903}
904
John McCall7ba107a2009-11-18 02:36:19 +0000905NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000906ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000907 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000908 = InstantiatedFromUsingDecl.find(UUD);
909 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000910 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Anders Carlsson0d8df782009-08-29 19:37:28 +0000912 return Pos->second;
913}
914
915void
John McCalled976492009-12-04 22:46:56 +0000916ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
917 assert((isa<UsingDecl>(Pattern) ||
918 isa<UnresolvedUsingValueDecl>(Pattern) ||
919 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
920 "pattern decl is not a using decl");
921 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
922 InstantiatedFromUsingDecl[Inst] = Pattern;
923}
924
925UsingShadowDecl *
926ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
927 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
928 = InstantiatedFromUsingShadowDecl.find(Inst);
929 if (Pos == InstantiatedFromUsingShadowDecl.end())
930 return 0;
931
932 return Pos->second;
933}
934
935void
936ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
937 UsingShadowDecl *Pattern) {
938 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
939 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000940}
941
Anders Carlssond8b285f2009-09-01 04:26:58 +0000942FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
943 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
944 = InstantiatedFromUnnamedFieldDecl.find(Field);
945 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
946 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Anders Carlssond8b285f2009-09-01 04:26:58 +0000948 return Pos->second;
949}
950
951void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
952 FieldDecl *Tmpl) {
953 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
954 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
955 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
956 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Anders Carlssond8b285f2009-09-01 04:26:58 +0000958 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
959}
960
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000961bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
962 const FieldDecl *LastFD) const {
963 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000964 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000965}
966
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000967bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
968 const FieldDecl *LastFD) const {
969 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000970 FD->getBitWidthValue(*this) == 0 &&
971 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000972}
973
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000974bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
975 const FieldDecl *LastFD) const {
976 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000977 FD->getBitWidthValue(*this) &&
978 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000979}
980
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000981bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000982 const FieldDecl *LastFD) const {
983 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000984 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000985}
986
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000987bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000988 const FieldDecl *LastFD) const {
989 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000990 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000991}
992
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000993ASTContext::overridden_cxx_method_iterator
994ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
995 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +0000996 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000997 if (Pos == OverriddenMethods.end())
998 return 0;
999
1000 return Pos->second.begin();
1001}
1002
1003ASTContext::overridden_cxx_method_iterator
1004ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1005 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001006 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001007 if (Pos == OverriddenMethods.end())
1008 return 0;
1009
1010 return Pos->second.end();
1011}
1012
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001013unsigned
1014ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1015 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001016 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001017 if (Pos == OverriddenMethods.end())
1018 return 0;
1019
1020 return Pos->second.size();
1021}
1022
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001023void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1024 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001025 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001026 OverriddenMethods[Method].push_back(Overridden);
1027}
1028
Douglas Gregore6649772011-12-03 00:30:27 +00001029void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1030 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1031 assert(!Import->isFromASTFile() && "Non-local import declaration");
1032 if (!FirstLocalImport) {
1033 FirstLocalImport = Import;
1034 LastLocalImport = Import;
1035 return;
1036 }
1037
1038 LastLocalImport->NextLocalImport = Import;
1039 LastLocalImport = Import;
1040}
1041
Chris Lattner464175b2007-07-18 17:52:12 +00001042//===----------------------------------------------------------------------===//
1043// Type Sizing and Analysis
1044//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001045
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001046/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1047/// scalar floating point type.
1048const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001049 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001050 assert(BT && "Not a floating point type!");
1051 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001052 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001053 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001054 case BuiltinType::Float: return Target->getFloatFormat();
1055 case BuiltinType::Double: return Target->getDoubleFormat();
1056 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001057 }
1058}
1059
Ken Dyck8b752f12010-01-27 17:10:57 +00001060/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001061/// specified decl. Note that bitfields do not have a valid alignment, so
1062/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001063/// If @p RefAsPointee, references are treated like their underlying type
1064/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001065CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001066 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001067
John McCall4081a5c2010-10-08 18:24:19 +00001068 bool UseAlignAttrOnly = false;
1069 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1070 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001071
John McCall4081a5c2010-10-08 18:24:19 +00001072 // __attribute__((aligned)) can increase or decrease alignment
1073 // *except* on a struct or struct member, where it only increases
1074 // alignment unless 'packed' is also specified.
1075 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001076 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001077 // ignore that possibility; Sema should diagnose it.
1078 if (isa<FieldDecl>(D)) {
1079 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1080 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1081 } else {
1082 UseAlignAttrOnly = true;
1083 }
1084 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001085 else if (isa<FieldDecl>(D))
1086 UseAlignAttrOnly =
1087 D->hasAttr<PackedAttr>() ||
1088 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001089
John McCallba4f5d52011-01-20 07:57:12 +00001090 // If we're using the align attribute only, just ignore everything
1091 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001092 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001093 // do nothing
1094
John McCall4081a5c2010-10-08 18:24:19 +00001095 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001096 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001097 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001098 if (RefAsPointee)
1099 T = RT->getPointeeType();
1100 else
1101 T = getPointerType(RT->getPointeeType());
1102 }
1103 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001104 // Adjust alignments of declarations with array type by the
1105 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001106 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001107 const ArrayType *arrayType;
1108 if (MinWidth && (arrayType = getAsArrayType(T))) {
1109 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001110 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001111 else if (isa<ConstantArrayType>(arrayType) &&
1112 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001113 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001114
John McCall3b657512011-01-19 10:06:00 +00001115 // Walk through any array types while we're at it.
1116 T = getBaseElementType(arrayType);
1117 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001118 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001119 }
John McCallba4f5d52011-01-20 07:57:12 +00001120
1121 // Fields can be subject to extra alignment constraints, like if
1122 // the field is packed, the struct is packed, or the struct has a
1123 // a max-field-alignment constraint (#pragma pack). So calculate
1124 // the actual alignment of the field within the struct, and then
1125 // (as we're expected to) constrain that by the alignment of the type.
1126 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1127 // So calculate the alignment of the field.
1128 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1129
1130 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001131 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001132
1133 // Use the GCD of that and the offset within the record.
1134 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1135 if (offset > 0) {
1136 // Alignment is always a power of 2, so the GCD will be a power of 2,
1137 // which means we get to do this crazy thing instead of Euclid's.
1138 uint64_t lowBitOfOffset = offset & (~offset + 1);
1139 if (lowBitOfOffset < fieldAlign)
1140 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1141 }
1142
1143 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001144 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001145 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001146
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001147 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001148}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001149
John McCall929bbfb2012-08-21 04:10:00 +00001150// getTypeInfoDataSizeInChars - Return the size of a type, in
1151// chars. If the type is a record, its data size is returned. This is
1152// the size of the memcpy that's performed when assigning this type
1153// using a trivial copy/move assignment operator.
1154std::pair<CharUnits, CharUnits>
1155ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1156 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1157
1158 // In C++, objects can sometimes be allocated into the tail padding
1159 // of a base-class subobject. We decide whether that's possible
1160 // during class layout, so here we can just trust the layout results.
1161 if (getLangOpts().CPlusPlus) {
1162 if (const RecordType *RT = T->getAs<RecordType>()) {
1163 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1164 sizeAndAlign.first = layout.getDataSize();
1165 }
1166 }
1167
1168 return sizeAndAlign;
1169}
1170
John McCallea1471e2010-05-20 01:18:31 +00001171std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001172ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001173 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001174 return std::make_pair(toCharUnitsFromBits(Info.first),
1175 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001176}
1177
1178std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001179ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001180 return getTypeInfoInChars(T.getTypePtr());
1181}
1182
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001183std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1184 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1185 if (it != MemoizedTypeInfo.end())
1186 return it->second;
1187
1188 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1189 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1190 return Info;
1191}
1192
1193/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1194/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001195///
1196/// FIXME: Pointers into different addr spaces could have different sizes and
1197/// alignment requirements: getPointerInfo should take an AddrSpace, this
1198/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001199std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001200ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001201 uint64_t Width=0;
1202 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001203 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001204#define TYPE(Class, Base)
1205#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001206#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001207#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1208#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001209 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001210
Chris Lattner692233e2007-07-13 22:27:08 +00001211 case Type::FunctionNoProto:
1212 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001213 // GCC extension: alignof(function) = 32 bits
1214 Width = 0;
1215 Align = 32;
1216 break;
1217
Douglas Gregor72564e72009-02-26 23:50:07 +00001218 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001219 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001220 Width = 0;
1221 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1222 break;
1223
Steve Narofffb22d962007-08-30 01:06:46 +00001224 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001225 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Chris Lattner98be4942008-03-05 18:54:05 +00001227 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001228 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001229 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1230 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001231 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001232 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001233 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001234 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001235 }
Nate Begeman213541a2008-04-18 23:10:10 +00001236 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001237 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001238 const VectorType *VT = cast<VectorType>(T);
1239 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1240 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001241 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001242 // If the alignment is not a power of 2, round up to the next power of 2.
1243 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001244 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001245 Align = llvm::NextPowerOf2(Align);
1246 Width = llvm::RoundUpToAlignment(Width, Align);
1247 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001248 // Adjust the alignment based on the target max.
1249 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1250 if (TargetVectorAlign && TargetVectorAlign < Align)
1251 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001252 break;
1253 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001254
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001255 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001256 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001257 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001258 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001259 // GCC extension: alignof(void) = 8 bits.
1260 Width = 0;
1261 Align = 8;
1262 break;
1263
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001264 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001265 Width = Target->getBoolWidth();
1266 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001267 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001268 case BuiltinType::Char_S:
1269 case BuiltinType::Char_U:
1270 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001271 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001272 Width = Target->getCharWidth();
1273 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001274 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001275 case BuiltinType::WChar_S:
1276 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001277 Width = Target->getWCharWidth();
1278 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001279 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001280 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001281 Width = Target->getChar16Width();
1282 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001283 break;
1284 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001285 Width = Target->getChar32Width();
1286 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001287 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001288 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001289 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001290 Width = Target->getShortWidth();
1291 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001292 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001293 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001294 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001295 Width = Target->getIntWidth();
1296 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001297 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001298 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001299 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001300 Width = Target->getLongWidth();
1301 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001302 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001303 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001304 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001305 Width = Target->getLongLongWidth();
1306 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001307 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001308 case BuiltinType::Int128:
1309 case BuiltinType::UInt128:
1310 Width = 128;
1311 Align = 128; // int128_t is 128-bit aligned on all targets.
1312 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001313 case BuiltinType::Half:
1314 Width = Target->getHalfWidth();
1315 Align = Target->getHalfAlign();
1316 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001317 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001318 Width = Target->getFloatWidth();
1319 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001320 break;
1321 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001322 Width = Target->getDoubleWidth();
1323 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001324 break;
1325 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001326 Width = Target->getLongDoubleWidth();
1327 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001328 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001329 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001330 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1331 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001332 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001333 case BuiltinType::ObjCId:
1334 case BuiltinType::ObjCClass:
1335 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001336 Width = Target->getPointerWidth(0);
1337 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001338 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001339 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001340 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001341 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001342 Width = Target->getPointerWidth(0);
1343 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001344 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001345 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001346 unsigned AS = getTargetAddressSpace(
1347 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001348 Width = Target->getPointerWidth(AS);
1349 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001350 break;
1351 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001352 case Type::LValueReference:
1353 case Type::RValueReference: {
1354 // alignof and sizeof should never enter this code path here, so we go
1355 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001356 unsigned AS = getTargetAddressSpace(
1357 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001358 Width = Target->getPointerWidth(AS);
1359 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001360 break;
1361 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001362 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001363 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001364 Width = Target->getPointerWidth(AS);
1365 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001366 break;
1367 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001368 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001369 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001370 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001371 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001372 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001373 Align = PtrDiffInfo.second;
1374 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001375 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001376 case Type::Complex: {
1377 // Complex types have the same alignment as their elements, but twice the
1378 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001379 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001380 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001381 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001382 Align = EltInfo.second;
1383 break;
1384 }
John McCallc12c5bb2010-05-15 11:32:37 +00001385 case Type::ObjCObject:
1386 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001387 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001388 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001389 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001390 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001391 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001392 break;
1393 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001394 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001395 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001396 const TagType *TT = cast<TagType>(T);
1397
1398 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001399 Width = 8;
1400 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001401 break;
1402 }
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Daniel Dunbar1d751182008-11-08 05:48:37 +00001404 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001405 return getTypeInfo(ET->getDecl()->getIntegerType());
1406
Daniel Dunbar1d751182008-11-08 05:48:37 +00001407 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001408 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001409 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001410 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001411 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001412 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001413
Chris Lattner9fcfe922009-10-22 05:17:15 +00001414 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001415 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1416 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001417
Richard Smith34b41d92011-02-20 03:19:35 +00001418 case Type::Auto: {
1419 const AutoType *A = cast<AutoType>(T);
1420 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001421 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001422 }
1423
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001424 case Type::Paren:
1425 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1426
Douglas Gregor18857642009-04-30 17:32:17 +00001427 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001428 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001429 std::pair<uint64_t, unsigned> Info
1430 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001431 // If the typedef has an aligned attribute on it, it overrides any computed
1432 // alignment we have. This violates the GCC documentation (which says that
1433 // attribute(aligned) can only round up) but matches its implementation.
1434 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1435 Align = AttrAlign;
1436 else
1437 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001438 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001439 break;
Chris Lattner71763312008-04-06 22:05:18 +00001440 }
Douglas Gregor18857642009-04-30 17:32:17 +00001441
1442 case Type::TypeOfExpr:
1443 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1444 .getTypePtr());
1445
1446 case Type::TypeOf:
1447 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1448
Anders Carlsson395b4752009-06-24 19:06:50 +00001449 case Type::Decltype:
1450 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1451 .getTypePtr());
1452
Sean Huntca63c202011-05-24 22:41:36 +00001453 case Type::UnaryTransform:
1454 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1455
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001456 case Type::Elaborated:
1457 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001458
John McCall9d156a72011-01-06 01:58:22 +00001459 case Type::Attributed:
1460 return getTypeInfo(
1461 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1462
Richard Smith3e4c6c42011-05-05 21:57:07 +00001463 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001464 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001465 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001466 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1467 // A type alias template specialization may refer to a typedef with the
1468 // aligned attribute on it.
1469 if (TST->isTypeAlias())
1470 return getTypeInfo(TST->getAliasedType().getTypePtr());
1471 else
1472 return getTypeInfo(getCanonicalType(T));
1473 }
1474
Eli Friedmanb001de72011-10-06 23:00:33 +00001475 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001476 std::pair<uint64_t, unsigned> Info
1477 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1478 Width = Info.first;
1479 Align = Info.second;
1480 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1481 llvm::isPowerOf2_64(Width)) {
1482 // We can potentially perform lock-free atomic operations for this
1483 // type; promote the alignment appropriately.
1484 // FIXME: We could potentially promote the width here as well...
1485 // is that worthwhile? (Non-struct atomic types generally have
1486 // power-of-two size anyway, but structs might not. Requires a bit
1487 // of implementation work to make sure we zero out the extra bits.)
1488 Align = static_cast<unsigned>(Width);
1489 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001490 }
1491
Douglas Gregor18857642009-04-30 17:32:17 +00001492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Eli Friedman2be46072011-10-14 20:59:01 +00001494 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001495 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001496}
1497
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001498/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1499CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1500 return CharUnits::fromQuantity(BitSize / getCharWidth());
1501}
1502
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001503/// toBits - Convert a size in characters to a size in characters.
1504int64_t ASTContext::toBits(CharUnits CharSize) const {
1505 return CharSize.getQuantity() * getCharWidth();
1506}
1507
Ken Dyckbdc601b2009-12-22 14:23:30 +00001508/// getTypeSizeInChars - Return the size of the specified type, in characters.
1509/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001510CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001511 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001512}
Jay Foad4ba2a172011-01-12 09:06:06 +00001513CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001514 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001515}
1516
Ken Dyck16e20cc2010-01-26 17:25:18 +00001517/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001518/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001519CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001520 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001521}
Jay Foad4ba2a172011-01-12 09:06:06 +00001522CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001523 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001524}
1525
Chris Lattner34ebde42009-01-27 18:08:34 +00001526/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1527/// type for the current target in bits. This can be different than the ABI
1528/// alignment in cases where it is beneficial for performance to overalign
1529/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001530unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001531 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001532
1533 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001534 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001535 T = CT->getElementType().getTypePtr();
1536 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001537 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1538 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001539 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1540
Chris Lattner34ebde42009-01-27 18:08:34 +00001541 return ABIAlign;
1542}
1543
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001544/// DeepCollectObjCIvars -
1545/// This routine first collects all declared, but not synthesized, ivars in
1546/// super class and then collects all ivars, including those synthesized for
1547/// current class. This routine is used for implementation of current class
1548/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001549///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001550void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1551 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001552 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001553 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1554 DeepCollectObjCIvars(SuperClass, false, Ivars);
1555 if (!leafClass) {
1556 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1557 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001558 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001559 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001560 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001561 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001562 Iv= Iv->getNextIvar())
1563 Ivars.push_back(Iv);
1564 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001565}
1566
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001567/// CollectInheritedProtocols - Collect all protocols in current class and
1568/// those inherited by it.
1569void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001570 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001571 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001572 // We can use protocol_iterator here instead of
1573 // all_referenced_protocol_iterator since we are walking all categories.
1574 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1575 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001576 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001577 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001578 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001579 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001580 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001581 CollectInheritedProtocols(*P, Protocols);
1582 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001583 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001584
1585 // Categories of this Interface.
1586 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1587 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1588 CollectInheritedProtocols(CDeclChain, Protocols);
1589 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1590 while (SD) {
1591 CollectInheritedProtocols(SD, Protocols);
1592 SD = SD->getSuperClass();
1593 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001594 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001595 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001596 PE = OC->protocol_end(); P != PE; ++P) {
1597 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001598 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001599 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1600 PE = Proto->protocol_end(); P != PE; ++P)
1601 CollectInheritedProtocols(*P, Protocols);
1602 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001603 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001604 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1605 PE = OP->protocol_end(); P != PE; ++P) {
1606 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001607 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001608 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1609 PE = Proto->protocol_end(); P != PE; ++P)
1610 CollectInheritedProtocols(*P, Protocols);
1611 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001612 }
1613}
1614
Jay Foad4ba2a172011-01-12 09:06:06 +00001615unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001616 unsigned count = 0;
1617 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001618 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1619 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001620 count += CDecl->ivar_size();
1621
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001622 // Count ivar defined in this class's implementation. This
1623 // includes synthesized ivars.
1624 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001625 count += ImplDecl->ivar_size();
1626
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001627 return count;
1628}
1629
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001630bool ASTContext::isSentinelNullExpr(const Expr *E) {
1631 if (!E)
1632 return false;
1633
1634 // nullptr_t is always treated as null.
1635 if (E->getType()->isNullPtrType()) return true;
1636
1637 if (E->getType()->isAnyPointerType() &&
1638 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1639 Expr::NPC_ValueDependentIsNull))
1640 return true;
1641
1642 // Unfortunately, __null has type 'int'.
1643 if (isa<GNUNullExpr>(E)) return true;
1644
1645 return false;
1646}
1647
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001648/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1649ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1650 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1651 I = ObjCImpls.find(D);
1652 if (I != ObjCImpls.end())
1653 return cast<ObjCImplementationDecl>(I->second);
1654 return 0;
1655}
1656/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1657ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1658 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1659 I = ObjCImpls.find(D);
1660 if (I != ObjCImpls.end())
1661 return cast<ObjCCategoryImplDecl>(I->second);
1662 return 0;
1663}
1664
1665/// \brief Set the implementation of ObjCInterfaceDecl.
1666void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1667 ObjCImplementationDecl *ImplD) {
1668 assert(IFaceD && ImplD && "Passed null params");
1669 ObjCImpls[IFaceD] = ImplD;
1670}
1671/// \brief Set the implementation of ObjCCategoryDecl.
1672void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1673 ObjCCategoryImplDecl *ImplD) {
1674 assert(CatD && ImplD && "Passed null params");
1675 ObjCImpls[CatD] = ImplD;
1676}
1677
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001678ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1679 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1680 return ID;
1681 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1682 return CD->getClassInterface();
1683 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1684 return IMD->getClassInterface();
1685
1686 return 0;
1687}
1688
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001689/// \brief Get the copy initialization expression of VarDecl,or NULL if
1690/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001691Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001692 assert(VD && "Passed null params");
1693 assert(VD->hasAttr<BlocksAttr>() &&
1694 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001695 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001696 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001697 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1698}
1699
1700/// \brief Set the copy inialization expression of a block var decl.
1701void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1702 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001703 assert(VD->hasAttr<BlocksAttr>() &&
1704 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001705 BlockVarCopyInits[VD] = Init;
1706}
1707
John McCalla93c9342009-12-07 02:54:59 +00001708TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001709 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001710 if (!DataSize)
1711 DataSize = TypeLoc::getFullDataSizeForType(T);
1712 else
1713 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001714 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001715
John McCalla93c9342009-12-07 02:54:59 +00001716 TypeSourceInfo *TInfo =
1717 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1718 new (TInfo) TypeSourceInfo(T);
1719 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001720}
1721
John McCalla93c9342009-12-07 02:54:59 +00001722TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001723 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001724 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001725 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001726 return DI;
1727}
1728
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001729const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001730ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001731 return getObjCLayout(D, 0);
1732}
1733
1734const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001735ASTContext::getASTObjCImplementationLayout(
1736 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001737 return getObjCLayout(D->getClassInterface(), D);
1738}
1739
Chris Lattnera7674d82007-07-13 22:13:22 +00001740//===----------------------------------------------------------------------===//
1741// Type creation/memoization methods
1742//===----------------------------------------------------------------------===//
1743
Jay Foad4ba2a172011-01-12 09:06:06 +00001744QualType
John McCall3b657512011-01-19 10:06:00 +00001745ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1746 unsigned fastQuals = quals.getFastQualifiers();
1747 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001748
1749 // Check if we've already instantiated this type.
1750 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001751 ExtQuals::Profile(ID, baseType, quals);
1752 void *insertPos = 0;
1753 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1754 assert(eq->getQualifiers() == quals);
1755 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001756 }
1757
John McCall3b657512011-01-19 10:06:00 +00001758 // If the base type is not canonical, make the appropriate canonical type.
1759 QualType canon;
1760 if (!baseType->isCanonicalUnqualified()) {
1761 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001762 canonSplit.Quals.addConsistentQualifiers(quals);
1763 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001764
1765 // Re-find the insert position.
1766 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1767 }
1768
1769 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1770 ExtQualNodes.InsertNode(eq, insertPos);
1771 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001772}
1773
Jay Foad4ba2a172011-01-12 09:06:06 +00001774QualType
1775ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001776 QualType CanT = getCanonicalType(T);
1777 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001778 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001779
John McCall0953e762009-09-24 19:53:00 +00001780 // If we are composing extended qualifiers together, merge together
1781 // into one ExtQuals node.
1782 QualifierCollector Quals;
1783 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001784
John McCall0953e762009-09-24 19:53:00 +00001785 // If this type already has an address space specified, it cannot get
1786 // another one.
1787 assert(!Quals.hasAddressSpace() &&
1788 "Type cannot be in multiple addr spaces!");
1789 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001790
John McCall0953e762009-09-24 19:53:00 +00001791 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001792}
1793
Chris Lattnerb7d25532009-02-18 22:53:11 +00001794QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001795 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001796 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001797 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001798 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001799
John McCall7f040a92010-12-24 02:08:15 +00001800 if (const PointerType *ptr = T->getAs<PointerType>()) {
1801 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001802 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001803 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1804 return getPointerType(ResultType);
1805 }
1806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807
John McCall0953e762009-09-24 19:53:00 +00001808 // If we are composing extended qualifiers together, merge together
1809 // into one ExtQuals node.
1810 QualifierCollector Quals;
1811 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001812
John McCall0953e762009-09-24 19:53:00 +00001813 // If this type already has an ObjCGC specified, it cannot get
1814 // another one.
1815 assert(!Quals.hasObjCGCAttr() &&
1816 "Type cannot have multiple ObjCGCs!");
1817 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
John McCall0953e762009-09-24 19:53:00 +00001819 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001820}
Chris Lattnera7674d82007-07-13 22:13:22 +00001821
John McCalle6a365d2010-12-19 02:44:49 +00001822const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1823 FunctionType::ExtInfo Info) {
1824 if (T->getExtInfo() == Info)
1825 return T;
1826
1827 QualType Result;
1828 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1829 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1830 } else {
1831 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1832 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1833 EPI.ExtInfo = Info;
1834 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1835 FPT->getNumArgs(), EPI);
1836 }
1837
1838 return cast<FunctionType>(Result.getTypePtr());
1839}
1840
Reid Spencer5f016e22007-07-11 17:01:13 +00001841/// getComplexType - Return the uniqued reference to the type for a complex
1842/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001843QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 // Unique pointers, to guarantee there is only one pointer of a particular
1845 // structure.
1846 llvm::FoldingSetNodeID ID;
1847 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 void *InsertPos = 0;
1850 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1851 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 // If the pointee type isn't canonical, this won't be a canonical type either,
1854 // so fill in the canonical type field.
1855 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001856 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001857 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 // Get the new insert position for the node we care about.
1860 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001861 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 }
John McCall6b304a02009-09-24 23:30:46 +00001863 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 Types.push_back(New);
1865 ComplexTypes.InsertNode(New, InsertPos);
1866 return QualType(New, 0);
1867}
1868
Reid Spencer5f016e22007-07-11 17:01:13 +00001869/// getPointerType - Return the uniqued reference to the type for a pointer to
1870/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001871QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001872 // Unique pointers, to guarantee there is only one pointer of a particular
1873 // structure.
1874 llvm::FoldingSetNodeID ID;
1875 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 void *InsertPos = 0;
1878 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1879 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 // If the pointee type isn't canonical, this won't be a canonical type either,
1882 // so fill in the canonical type field.
1883 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001884 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001885 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 // Get the new insert position for the node we care about.
1888 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001889 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 }
John McCall6b304a02009-09-24 23:30:46 +00001891 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001892 Types.push_back(New);
1893 PointerTypes.InsertNode(New, InsertPos);
1894 return QualType(New, 0);
1895}
1896
Mike Stump1eb44332009-09-09 15:08:12 +00001897/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001898/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001899QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001900 assert(T->isFunctionType() && "block of function types only");
1901 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001902 // structure.
1903 llvm::FoldingSetNodeID ID;
1904 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Steve Naroff5618bd42008-08-27 16:04:49 +00001906 void *InsertPos = 0;
1907 if (BlockPointerType *PT =
1908 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1909 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001910
1911 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001912 // type either so fill in the canonical type field.
1913 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001914 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001915 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Steve Naroff5618bd42008-08-27 16:04:49 +00001917 // Get the new insert position for the node we care about.
1918 BlockPointerType *NewIP =
1919 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001920 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001921 }
John McCall6b304a02009-09-24 23:30:46 +00001922 BlockPointerType *New
1923 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001924 Types.push_back(New);
1925 BlockPointerTypes.InsertNode(New, InsertPos);
1926 return QualType(New, 0);
1927}
1928
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001929/// getLValueReferenceType - Return the uniqued reference to the type for an
1930/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001931QualType
1932ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001933 assert(getCanonicalType(T) != OverloadTy &&
1934 "Unresolved overloaded function type");
1935
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 // Unique pointers, to guarantee there is only one pointer of a particular
1937 // structure.
1938 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001939 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001940
1941 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001942 if (LValueReferenceType *RT =
1943 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001945
John McCall54e14c42009-10-22 22:37:11 +00001946 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1947
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 // If the referencee type isn't canonical, this won't be a canonical type
1949 // either, so fill in the canonical type field.
1950 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001951 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1952 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1953 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001954
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001956 LValueReferenceType *NewIP =
1957 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001958 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 }
1960
John McCall6b304a02009-09-24 23:30:46 +00001961 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001962 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1963 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001965 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001966
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001967 return QualType(New, 0);
1968}
1969
1970/// getRValueReferenceType - Return the uniqued reference to the type for an
1971/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001972QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001973 // Unique pointers, to guarantee there is only one pointer of a particular
1974 // structure.
1975 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001976 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001977
1978 void *InsertPos = 0;
1979 if (RValueReferenceType *RT =
1980 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1981 return QualType(RT, 0);
1982
John McCall54e14c42009-10-22 22:37:11 +00001983 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1984
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001985 // If the referencee type isn't canonical, this won't be a canonical type
1986 // either, so fill in the canonical type field.
1987 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001988 if (InnerRef || !T.isCanonical()) {
1989 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1990 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001991
1992 // Get the new insert position for the node we care about.
1993 RValueReferenceType *NewIP =
1994 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001995 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001996 }
1997
John McCall6b304a02009-09-24 23:30:46 +00001998 RValueReferenceType *New
1999 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002000 Types.push_back(New);
2001 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 return QualType(New, 0);
2003}
2004
Sebastian Redlf30208a2009-01-24 21:16:55 +00002005/// getMemberPointerType - Return the uniqued reference to the type for a
2006/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002007QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002008 // Unique pointers, to guarantee there is only one pointer of a particular
2009 // structure.
2010 llvm::FoldingSetNodeID ID;
2011 MemberPointerType::Profile(ID, T, Cls);
2012
2013 void *InsertPos = 0;
2014 if (MemberPointerType *PT =
2015 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2016 return QualType(PT, 0);
2017
2018 // If the pointee or class type isn't canonical, this won't be a canonical
2019 // type either, so fill in the canonical type field.
2020 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002021 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002022 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2023
2024 // Get the new insert position for the node we care about.
2025 MemberPointerType *NewIP =
2026 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002027 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002028 }
John McCall6b304a02009-09-24 23:30:46 +00002029 MemberPointerType *New
2030 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002031 Types.push_back(New);
2032 MemberPointerTypes.InsertNode(New, InsertPos);
2033 return QualType(New, 0);
2034}
2035
Mike Stump1eb44332009-09-09 15:08:12 +00002036/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002037/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002038QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002039 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002040 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002041 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002042 assert((EltTy->isDependentType() ||
2043 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002044 "Constant array of VLAs is illegal!");
2045
Chris Lattner38aeec72009-05-13 04:12:56 +00002046 // Convert the array size into a canonical width matching the pointer size for
2047 // the target.
2048 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002049 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002050 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002053 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002056 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002057 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
John McCall3b657512011-01-19 10:06:00 +00002060 // If the element type isn't canonical or has qualifiers, this won't
2061 // be a canonical type either, so fill in the canonical type field.
2062 QualType Canon;
2063 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2064 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002065 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002066 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002067 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002068
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002070 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002071 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002072 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
John McCall6b304a02009-09-24 23:30:46 +00002075 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002076 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002077 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 Types.push_back(New);
2079 return QualType(New, 0);
2080}
2081
John McCallce889032011-01-18 08:40:38 +00002082/// getVariableArrayDecayedType - Turns the given type, which may be
2083/// variably-modified, into the corresponding type with all the known
2084/// sizes replaced with [*].
2085QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2086 // Vastly most common case.
2087 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002088
John McCallce889032011-01-18 08:40:38 +00002089 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002090
John McCallce889032011-01-18 08:40:38 +00002091 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002092 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002093 switch (ty->getTypeClass()) {
2094#define TYPE(Class, Base)
2095#define ABSTRACT_TYPE(Class, Base)
2096#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2097#include "clang/AST/TypeNodes.def"
2098 llvm_unreachable("didn't desugar past all non-canonical types?");
2099
2100 // These types should never be variably-modified.
2101 case Type::Builtin:
2102 case Type::Complex:
2103 case Type::Vector:
2104 case Type::ExtVector:
2105 case Type::DependentSizedExtVector:
2106 case Type::ObjCObject:
2107 case Type::ObjCInterface:
2108 case Type::ObjCObjectPointer:
2109 case Type::Record:
2110 case Type::Enum:
2111 case Type::UnresolvedUsing:
2112 case Type::TypeOfExpr:
2113 case Type::TypeOf:
2114 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002115 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002116 case Type::DependentName:
2117 case Type::InjectedClassName:
2118 case Type::TemplateSpecialization:
2119 case Type::DependentTemplateSpecialization:
2120 case Type::TemplateTypeParm:
2121 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002122 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002123 case Type::PackExpansion:
2124 llvm_unreachable("type should never be variably-modified");
2125
2126 // These types can be variably-modified but should never need to
2127 // further decay.
2128 case Type::FunctionNoProto:
2129 case Type::FunctionProto:
2130 case Type::BlockPointer:
2131 case Type::MemberPointer:
2132 return type;
2133
2134 // These types can be variably-modified. All these modifications
2135 // preserve structure except as noted by comments.
2136 // TODO: if we ever care about optimizing VLAs, there are no-op
2137 // optimizations available here.
2138 case Type::Pointer:
2139 result = getPointerType(getVariableArrayDecayedType(
2140 cast<PointerType>(ty)->getPointeeType()));
2141 break;
2142
2143 case Type::LValueReference: {
2144 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2145 result = getLValueReferenceType(
2146 getVariableArrayDecayedType(lv->getPointeeType()),
2147 lv->isSpelledAsLValue());
2148 break;
2149 }
2150
2151 case Type::RValueReference: {
2152 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2153 result = getRValueReferenceType(
2154 getVariableArrayDecayedType(lv->getPointeeType()));
2155 break;
2156 }
2157
Eli Friedmanb001de72011-10-06 23:00:33 +00002158 case Type::Atomic: {
2159 const AtomicType *at = cast<AtomicType>(ty);
2160 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2161 break;
2162 }
2163
John McCallce889032011-01-18 08:40:38 +00002164 case Type::ConstantArray: {
2165 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2166 result = getConstantArrayType(
2167 getVariableArrayDecayedType(cat->getElementType()),
2168 cat->getSize(),
2169 cat->getSizeModifier(),
2170 cat->getIndexTypeCVRQualifiers());
2171 break;
2172 }
2173
2174 case Type::DependentSizedArray: {
2175 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2176 result = getDependentSizedArrayType(
2177 getVariableArrayDecayedType(dat->getElementType()),
2178 dat->getSizeExpr(),
2179 dat->getSizeModifier(),
2180 dat->getIndexTypeCVRQualifiers(),
2181 dat->getBracketsRange());
2182 break;
2183 }
2184
2185 // Turn incomplete types into [*] types.
2186 case Type::IncompleteArray: {
2187 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2188 result = getVariableArrayType(
2189 getVariableArrayDecayedType(iat->getElementType()),
2190 /*size*/ 0,
2191 ArrayType::Normal,
2192 iat->getIndexTypeCVRQualifiers(),
2193 SourceRange());
2194 break;
2195 }
2196
2197 // Turn VLA types into [*] types.
2198 case Type::VariableArray: {
2199 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2200 result = getVariableArrayType(
2201 getVariableArrayDecayedType(vat->getElementType()),
2202 /*size*/ 0,
2203 ArrayType::Star,
2204 vat->getIndexTypeCVRQualifiers(),
2205 vat->getBracketsRange());
2206 break;
2207 }
2208 }
2209
2210 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002211 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002212}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002213
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002214/// getVariableArrayType - Returns a non-unique reference to the type for a
2215/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002216QualType ASTContext::getVariableArrayType(QualType EltTy,
2217 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002218 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002219 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002220 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002221 // Since we don't unique expressions, it isn't possible to unique VLA's
2222 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002223 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002224
John McCall3b657512011-01-19 10:06:00 +00002225 // Be sure to pull qualifiers off the element type.
2226 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2227 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002228 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002229 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002230 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002231 }
2232
John McCall6b304a02009-09-24 23:30:46 +00002233 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002234 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002235
2236 VariableArrayTypes.push_back(New);
2237 Types.push_back(New);
2238 return QualType(New, 0);
2239}
2240
Douglas Gregor898574e2008-12-05 23:32:09 +00002241/// getDependentSizedArrayType - Returns a non-unique reference to
2242/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002243/// type.
John McCall3b657512011-01-19 10:06:00 +00002244QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2245 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002246 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002247 unsigned elementTypeQuals,
2248 SourceRange brackets) const {
2249 assert((!numElements || numElements->isTypeDependent() ||
2250 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002251 "Size must be type- or value-dependent!");
2252
John McCall3b657512011-01-19 10:06:00 +00002253 // Dependently-sized array types that do not have a specified number
2254 // of elements will have their sizes deduced from a dependent
2255 // initializer. We do no canonicalization here at all, which is okay
2256 // because they can't be used in most locations.
2257 if (!numElements) {
2258 DependentSizedArrayType *newType
2259 = new (*this, TypeAlignment)
2260 DependentSizedArrayType(*this, elementType, QualType(),
2261 numElements, ASM, elementTypeQuals,
2262 brackets);
2263 Types.push_back(newType);
2264 return QualType(newType, 0);
2265 }
2266
2267 // Otherwise, we actually build a new type every time, but we
2268 // also build a canonical type.
2269
2270 SplitQualType canonElementType = getCanonicalType(elementType).split();
2271
2272 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002273 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002274 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002275 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002276 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002277
John McCall3b657512011-01-19 10:06:00 +00002278 // Look for an existing type with these properties.
2279 DependentSizedArrayType *canonTy =
2280 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002281
John McCall3b657512011-01-19 10:06:00 +00002282 // If we don't have one, build one.
2283 if (!canonTy) {
2284 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002285 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002286 QualType(), numElements, ASM, elementTypeQuals,
2287 brackets);
2288 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2289 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002290 }
2291
John McCall3b657512011-01-19 10:06:00 +00002292 // Apply qualifiers from the element type to the array.
2293 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002294 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002295
John McCall3b657512011-01-19 10:06:00 +00002296 // If we didn't need extra canonicalization for the element type,
2297 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002298 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002299 return canon;
2300
2301 // Otherwise, we need to build a type which follows the spelling
2302 // of the element type.
2303 DependentSizedArrayType *sugaredType
2304 = new (*this, TypeAlignment)
2305 DependentSizedArrayType(*this, elementType, canon, numElements,
2306 ASM, elementTypeQuals, brackets);
2307 Types.push_back(sugaredType);
2308 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002309}
2310
John McCall3b657512011-01-19 10:06:00 +00002311QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002312 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002313 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002314 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002315 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002316
John McCall3b657512011-01-19 10:06:00 +00002317 void *insertPos = 0;
2318 if (IncompleteArrayType *iat =
2319 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2320 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002321
2322 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002323 // either, so fill in the canonical type field. We also have to pull
2324 // qualifiers off the element type.
2325 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002326
John McCall3b657512011-01-19 10:06:00 +00002327 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2328 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002329 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002330 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002331 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002332
2333 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002334 IncompleteArrayType *existing =
2335 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2336 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002337 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002338
John McCall3b657512011-01-19 10:06:00 +00002339 IncompleteArrayType *newType = new (*this, TypeAlignment)
2340 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002341
John McCall3b657512011-01-19 10:06:00 +00002342 IncompleteArrayTypes.InsertNode(newType, insertPos);
2343 Types.push_back(newType);
2344 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002345}
2346
Steve Naroff73322922007-07-18 18:00:27 +00002347/// getVectorType - Return the unique reference to a vector type of
2348/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002349QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002350 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002351 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 // Check if we've already instantiated a vector of this type.
2354 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002355 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002356
Reid Spencer5f016e22007-07-11 17:01:13 +00002357 void *InsertPos = 0;
2358 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2359 return QualType(VTP, 0);
2360
2361 // If the element type isn't canonical, this won't be a canonical type either,
2362 // so fill in the canonical type field.
2363 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002364 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002365 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 // Get the new insert position for the node we care about.
2368 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002369 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 }
John McCall6b304a02009-09-24 23:30:46 +00002371 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002372 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 VectorTypes.InsertNode(New, InsertPos);
2374 Types.push_back(New);
2375 return QualType(New, 0);
2376}
2377
Nate Begeman213541a2008-04-18 23:10:10 +00002378/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002379/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002380QualType
2381ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002382 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Steve Naroff73322922007-07-18 18:00:27 +00002384 // Check if we've already instantiated a vector of this type.
2385 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002386 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002387 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002388 void *InsertPos = 0;
2389 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2390 return QualType(VTP, 0);
2391
2392 // If the element type isn't canonical, this won't be a canonical type either,
2393 // so fill in the canonical type field.
2394 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002395 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002396 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Steve Naroff73322922007-07-18 18:00:27 +00002398 // Get the new insert position for the node we care about.
2399 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002400 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002401 }
John McCall6b304a02009-09-24 23:30:46 +00002402 ExtVectorType *New = new (*this, TypeAlignment)
2403 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002404 VectorTypes.InsertNode(New, InsertPos);
2405 Types.push_back(New);
2406 return QualType(New, 0);
2407}
2408
Jay Foad4ba2a172011-01-12 09:06:06 +00002409QualType
2410ASTContext::getDependentSizedExtVectorType(QualType vecType,
2411 Expr *SizeExpr,
2412 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002413 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002414 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002415 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002417 void *InsertPos = 0;
2418 DependentSizedExtVectorType *Canon
2419 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2420 DependentSizedExtVectorType *New;
2421 if (Canon) {
2422 // We already have a canonical version of this array type; use it as
2423 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002424 New = new (*this, TypeAlignment)
2425 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2426 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002427 } else {
2428 QualType CanonVecTy = getCanonicalType(vecType);
2429 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002430 New = new (*this, TypeAlignment)
2431 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2432 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002433
2434 DependentSizedExtVectorType *CanonCheck
2435 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2436 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2437 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002438 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2439 } else {
2440 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2441 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002442 New = new (*this, TypeAlignment)
2443 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002444 }
2445 }
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002447 Types.push_back(New);
2448 return QualType(New, 0);
2449}
2450
Douglas Gregor72564e72009-02-26 23:50:07 +00002451/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002452///
Jay Foad4ba2a172011-01-12 09:06:06 +00002453QualType
2454ASTContext::getFunctionNoProtoType(QualType ResultTy,
2455 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002456 const CallingConv DefaultCC = Info.getCC();
2457 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2458 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 // Unique functions, to guarantee there is only one function of a particular
2460 // structure.
2461 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002462 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002465 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002466 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002467 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Reid Spencer5f016e22007-07-11 17:01:13 +00002469 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002470 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002471 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002472 Canonical =
2473 getFunctionNoProtoType(getCanonicalType(ResultTy),
2474 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002475
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002477 FunctionNoProtoType *NewIP =
2478 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002479 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002480 }
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Roman Divackycfe9af22011-03-01 17:40:53 +00002482 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002483 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002484 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002486 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 return QualType(New, 0);
2488}
2489
2490/// getFunctionType - Return a normal function type with a typed argument
2491/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002492QualType
2493ASTContext::getFunctionType(QualType ResultTy,
2494 const QualType *ArgArray, unsigned NumArgs,
2495 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002496 // Unique functions, to guarantee there is only one function of a particular
2497 // structure.
2498 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002499 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002500
2501 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002502 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002503 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002504 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002505
2506 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002507 bool isCanonical =
2508 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2509 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002510 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002511 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002512 isCanonical = false;
2513
Roman Divackycfe9af22011-03-01 17:40:53 +00002514 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2515 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2516 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002517
Reid Spencer5f016e22007-07-11 17:01:13 +00002518 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002519 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002521 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002522 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 CanonicalArgs.reserve(NumArgs);
2524 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002525 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002526
John McCalle23cf432010-12-14 08:05:40 +00002527 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002528 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002529 CanonicalEPI.ExceptionSpecType = EST_None;
2530 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002531 CanonicalEPI.ExtInfo
2532 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2533
Chris Lattnerf52ab252008-04-06 22:59:24 +00002534 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002535 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002536 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002537
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002539 FunctionProtoType *NewIP =
2540 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002541 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002543
John McCallf85e1932011-06-15 23:02:42 +00002544 // FunctionProtoType objects are allocated with extra bytes after
2545 // them for three variable size arrays at the end:
2546 // - parameter types
2547 // - exception types
2548 // - consumed-arguments flags
2549 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002550 // expression, or information used to resolve the exception
2551 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002552 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002553 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002554 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002555 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002556 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002557 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002558 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002559 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002560 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2561 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002562 }
John McCallf85e1932011-06-15 23:02:42 +00002563 if (EPI.ConsumedArguments)
2564 Size += NumArgs * sizeof(bool);
2565
John McCalle23cf432010-12-14 08:05:40 +00002566 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002567 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2568 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002569 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002571 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 return QualType(FTP, 0);
2573}
2574
John McCall3cb0ebd2010-03-10 03:28:59 +00002575#ifndef NDEBUG
2576static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2577 if (!isa<CXXRecordDecl>(D)) return false;
2578 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2579 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2580 return true;
2581 if (RD->getDescribedClassTemplate() &&
2582 !isa<ClassTemplateSpecializationDecl>(RD))
2583 return true;
2584 return false;
2585}
2586#endif
2587
2588/// getInjectedClassNameType - Return the unique reference to the
2589/// injected class name type for the specified templated declaration.
2590QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002591 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002592 assert(NeedsInjectedClassNameType(Decl));
2593 if (Decl->TypeForDecl) {
2594 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002595 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002596 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2597 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2598 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2599 } else {
John McCallf4c73712011-01-19 06:33:43 +00002600 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002601 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002602 Decl->TypeForDecl = newType;
2603 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002604 }
2605 return QualType(Decl->TypeForDecl, 0);
2606}
2607
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002608/// getTypeDeclType - Return the unique reference to the type for the
2609/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002610QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002611 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002612 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002613
Richard Smith162e1c12011-04-15 14:24:37 +00002614 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002615 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002616
John McCallbecb8d52010-03-10 06:48:02 +00002617 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2618 "Template type parameter types are always available.");
2619
John McCall19c85762010-02-16 03:57:14 +00002620 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002621 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002622 "struct/union has previous declaration");
2623 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002624 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002625 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002626 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002627 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002628 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002629 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002630 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002631 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2632 Decl->TypeForDecl = newType;
2633 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002634 } else
John McCallbecb8d52010-03-10 06:48:02 +00002635 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002636
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002637 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002638}
2639
Reid Spencer5f016e22007-07-11 17:01:13 +00002640/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002641/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002642QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002643ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2644 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002647 if (Canonical.isNull())
2648 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002649 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002650 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002651 Decl->TypeForDecl = newType;
2652 Types.push_back(newType);
2653 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002654}
2655
Jay Foad4ba2a172011-01-12 09:06:06 +00002656QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002657 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2658
Douglas Gregoref96ee02012-01-14 16:38:05 +00002659 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002660 if (PrevDecl->TypeForDecl)
2661 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2662
John McCallf4c73712011-01-19 06:33:43 +00002663 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2664 Decl->TypeForDecl = newType;
2665 Types.push_back(newType);
2666 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002667}
2668
Jay Foad4ba2a172011-01-12 09:06:06 +00002669QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002670 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2671
Douglas Gregoref96ee02012-01-14 16:38:05 +00002672 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002673 if (PrevDecl->TypeForDecl)
2674 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2675
John McCallf4c73712011-01-19 06:33:43 +00002676 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2677 Decl->TypeForDecl = newType;
2678 Types.push_back(newType);
2679 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002680}
2681
John McCall9d156a72011-01-06 01:58:22 +00002682QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2683 QualType modifiedType,
2684 QualType equivalentType) {
2685 llvm::FoldingSetNodeID id;
2686 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2687
2688 void *insertPos = 0;
2689 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2690 if (type) return QualType(type, 0);
2691
2692 QualType canon = getCanonicalType(equivalentType);
2693 type = new (*this, TypeAlignment)
2694 AttributedType(canon, attrKind, modifiedType, equivalentType);
2695
2696 Types.push_back(type);
2697 AttributedTypes.InsertNode(type, insertPos);
2698
2699 return QualType(type, 0);
2700}
2701
2702
John McCall49a832b2009-10-18 09:09:24 +00002703/// \brief Retrieve a substitution-result type.
2704QualType
2705ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002706 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002707 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002708 && "replacement types must always be canonical");
2709
2710 llvm::FoldingSetNodeID ID;
2711 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2712 void *InsertPos = 0;
2713 SubstTemplateTypeParmType *SubstParm
2714 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2715
2716 if (!SubstParm) {
2717 SubstParm = new (*this, TypeAlignment)
2718 SubstTemplateTypeParmType(Parm, Replacement);
2719 Types.push_back(SubstParm);
2720 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2721 }
2722
2723 return QualType(SubstParm, 0);
2724}
2725
Douglas Gregorc3069d62011-01-14 02:55:32 +00002726/// \brief Retrieve a
2727QualType ASTContext::getSubstTemplateTypeParmPackType(
2728 const TemplateTypeParmType *Parm,
2729 const TemplateArgument &ArgPack) {
2730#ifndef NDEBUG
2731 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2732 PEnd = ArgPack.pack_end();
2733 P != PEnd; ++P) {
2734 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2735 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2736 }
2737#endif
2738
2739 llvm::FoldingSetNodeID ID;
2740 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2741 void *InsertPos = 0;
2742 if (SubstTemplateTypeParmPackType *SubstParm
2743 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2744 return QualType(SubstParm, 0);
2745
2746 QualType Canon;
2747 if (!Parm->isCanonicalUnqualified()) {
2748 Canon = getCanonicalType(QualType(Parm, 0));
2749 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2750 ArgPack);
2751 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2752 }
2753
2754 SubstTemplateTypeParmPackType *SubstParm
2755 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2756 ArgPack);
2757 Types.push_back(SubstParm);
2758 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2759 return QualType(SubstParm, 0);
2760}
2761
Douglas Gregorfab9d672009-02-05 23:33:38 +00002762/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002763/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002764/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002765QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002766 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002767 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002768 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002769 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002770 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002771 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002772 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2773
2774 if (TypeParm)
2775 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002777 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002778 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002779 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002780
2781 TemplateTypeParmType *TypeCheck
2782 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2783 assert(!TypeCheck && "Template type parameter canonical type broken");
2784 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002785 } else
John McCall6b304a02009-09-24 23:30:46 +00002786 TypeParm = new (*this, TypeAlignment)
2787 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002788
2789 Types.push_back(TypeParm);
2790 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2791
2792 return QualType(TypeParm, 0);
2793}
2794
John McCall3cb0ebd2010-03-10 03:28:59 +00002795TypeSourceInfo *
2796ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2797 SourceLocation NameLoc,
2798 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002799 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002800 assert(!Name.getAsDependentTemplateName() &&
2801 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002802 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002803
2804 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2805 TemplateSpecializationTypeLoc TL
2806 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002807 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002808 TL.setTemplateNameLoc(NameLoc);
2809 TL.setLAngleLoc(Args.getLAngleLoc());
2810 TL.setRAngleLoc(Args.getRAngleLoc());
2811 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2812 TL.setArgLocInfo(i, Args[i].getLocInfo());
2813 return DI;
2814}
2815
Mike Stump1eb44332009-09-09 15:08:12 +00002816QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002817ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002818 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002819 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002820 assert(!Template.getAsDependentTemplateName() &&
2821 "No dependent template names here!");
2822
John McCalld5532b62009-11-23 01:53:49 +00002823 unsigned NumArgs = Args.size();
2824
Chris Lattner5f9e2722011-07-23 10:55:15 +00002825 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002826 ArgVec.reserve(NumArgs);
2827 for (unsigned i = 0; i != NumArgs; ++i)
2828 ArgVec.push_back(Args[i].getArgument());
2829
John McCall31f17ec2010-04-27 00:57:59 +00002830 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002831 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002832}
2833
Douglas Gregorb70126a2012-02-03 17:16:23 +00002834#ifndef NDEBUG
2835static bool hasAnyPackExpansions(const TemplateArgument *Args,
2836 unsigned NumArgs) {
2837 for (unsigned I = 0; I != NumArgs; ++I)
2838 if (Args[I].isPackExpansion())
2839 return true;
2840
2841 return true;
2842}
2843#endif
2844
John McCall833ca992009-10-29 08:12:44 +00002845QualType
2846ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002847 const TemplateArgument *Args,
2848 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002849 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002850 assert(!Template.getAsDependentTemplateName() &&
2851 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002852 // Look through qualified template names.
2853 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2854 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002855
Douglas Gregorb70126a2012-02-03 17:16:23 +00002856 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002857 Template.getAsTemplateDecl() &&
2858 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002859 QualType CanonType;
2860 if (!Underlying.isNull())
2861 CanonType = getCanonicalType(Underlying);
2862 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002863 // We can get here with an alias template when the specialization contains
2864 // a pack expansion that does not match up with a parameter pack.
2865 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2866 "Caller must compute aliased type");
2867 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002868 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2869 NumArgs);
2870 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002871
Douglas Gregor1275ae02009-07-28 23:00:59 +00002872 // Allocate the (non-canonical) template specialization type, but don't
2873 // try to unique it: these types typically have location information that
2874 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002875 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2876 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002877 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002878 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002879 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002880 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2881 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Douglas Gregor55f6b142009-02-09 18:46:07 +00002883 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002884 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002885}
2886
Mike Stump1eb44332009-09-09 15:08:12 +00002887QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002888ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2889 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002890 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002891 assert(!Template.getAsDependentTemplateName() &&
2892 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002893
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002894 // Look through qualified template names.
2895 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2896 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002897
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002898 // Build the canonical template specialization type.
2899 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002900 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002901 CanonArgs.reserve(NumArgs);
2902 for (unsigned I = 0; I != NumArgs; ++I)
2903 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2904
2905 // Determine whether this canonical template specialization type already
2906 // exists.
2907 llvm::FoldingSetNodeID ID;
2908 TemplateSpecializationType::Profile(ID, CanonTemplate,
2909 CanonArgs.data(), NumArgs, *this);
2910
2911 void *InsertPos = 0;
2912 TemplateSpecializationType *Spec
2913 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2914
2915 if (!Spec) {
2916 // Allocate a new canonical template specialization type.
2917 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2918 sizeof(TemplateArgument) * NumArgs),
2919 TypeAlignment);
2920 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2921 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002922 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002923 Types.push_back(Spec);
2924 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2925 }
2926
2927 assert(Spec->isDependentType() &&
2928 "Non-dependent template-id type must have a canonical type");
2929 return QualType(Spec, 0);
2930}
2931
2932QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002933ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2934 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002935 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002936 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002937 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002938
2939 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002940 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002941 if (T)
2942 return QualType(T, 0);
2943
Douglas Gregor789b1f62010-02-04 18:10:26 +00002944 QualType Canon = NamedType;
2945 if (!Canon.isCanonical()) {
2946 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002947 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2948 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002949 (void)CheckT;
2950 }
2951
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002952 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002953 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002954 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002955 return QualType(T, 0);
2956}
2957
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002958QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002959ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002960 llvm::FoldingSetNodeID ID;
2961 ParenType::Profile(ID, InnerType);
2962
2963 void *InsertPos = 0;
2964 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2965 if (T)
2966 return QualType(T, 0);
2967
2968 QualType Canon = InnerType;
2969 if (!Canon.isCanonical()) {
2970 Canon = getCanonicalType(InnerType);
2971 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2972 assert(!CheckT && "Paren canonical type broken");
2973 (void)CheckT;
2974 }
2975
2976 T = new (*this) ParenType(InnerType, Canon);
2977 Types.push_back(T);
2978 ParenTypes.InsertNode(T, InsertPos);
2979 return QualType(T, 0);
2980}
2981
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002982QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2983 NestedNameSpecifier *NNS,
2984 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002985 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002986 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2987
2988 if (Canon.isNull()) {
2989 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002990 ElaboratedTypeKeyword CanonKeyword = Keyword;
2991 if (Keyword == ETK_None)
2992 CanonKeyword = ETK_Typename;
2993
2994 if (CanonNNS != NNS || CanonKeyword != Keyword)
2995 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002996 }
2997
2998 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002999 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003000
3001 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003002 DependentNameType *T
3003 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003004 if (T)
3005 return QualType(T, 0);
3006
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003007 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003008 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003009 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003010 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003011}
3012
Mike Stump1eb44332009-09-09 15:08:12 +00003013QualType
John McCall33500952010-06-11 00:33:02 +00003014ASTContext::getDependentTemplateSpecializationType(
3015 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003016 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003017 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003018 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003019 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003020 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003021 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3022 ArgCopy.push_back(Args[I].getArgument());
3023 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3024 ArgCopy.size(),
3025 ArgCopy.data());
3026}
3027
3028QualType
3029ASTContext::getDependentTemplateSpecializationType(
3030 ElaboratedTypeKeyword Keyword,
3031 NestedNameSpecifier *NNS,
3032 const IdentifierInfo *Name,
3033 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003034 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003035 assert((!NNS || NNS->isDependent()) &&
3036 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003037
Douglas Gregor789b1f62010-02-04 18:10:26 +00003038 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003039 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3040 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003041
3042 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003043 DependentTemplateSpecializationType *T
3044 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003045 if (T)
3046 return QualType(T, 0);
3047
John McCall33500952010-06-11 00:33:02 +00003048 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003049
John McCall33500952010-06-11 00:33:02 +00003050 ElaboratedTypeKeyword CanonKeyword = Keyword;
3051 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3052
3053 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003054 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003055 for (unsigned I = 0; I != NumArgs; ++I) {
3056 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3057 if (!CanonArgs[I].structurallyEquals(Args[I]))
3058 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003059 }
3060
John McCall33500952010-06-11 00:33:02 +00003061 QualType Canon;
3062 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3063 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3064 Name, NumArgs,
3065 CanonArgs.data());
3066
3067 // Find the insert position again.
3068 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3069 }
3070
3071 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3072 sizeof(TemplateArgument) * NumArgs),
3073 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003074 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003075 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003076 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003077 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003078 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003079}
3080
Douglas Gregorcded4f62011-01-14 17:04:44 +00003081QualType ASTContext::getPackExpansionType(QualType Pattern,
3082 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003083 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003084 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003085
3086 assert(Pattern->containsUnexpandedParameterPack() &&
3087 "Pack expansions must expand one or more parameter packs");
3088 void *InsertPos = 0;
3089 PackExpansionType *T
3090 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3091 if (T)
3092 return QualType(T, 0);
3093
3094 QualType Canon;
3095 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003096 Canon = getCanonicalType(Pattern);
3097 // The canonical type might not contain an unexpanded parameter pack, if it
3098 // contains an alias template specialization which ignores one of its
3099 // parameters.
3100 if (Canon->containsUnexpandedParameterPack()) {
3101 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003102
Richard Smithd8672ef2012-07-16 00:20:35 +00003103 // Find the insert position again, in case we inserted an element into
3104 // PackExpansionTypes and invalidated our insert position.
3105 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3106 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003107 }
3108
Douglas Gregorcded4f62011-01-14 17:04:44 +00003109 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003110 Types.push_back(T);
3111 PackExpansionTypes.InsertNode(T, InsertPos);
3112 return QualType(T, 0);
3113}
3114
Chris Lattner88cb27a2008-04-07 04:56:42 +00003115/// CmpProtocolNames - Comparison predicate for sorting protocols
3116/// alphabetically.
3117static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3118 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003119 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003120}
3121
John McCallc12c5bb2010-05-15 11:32:37 +00003122static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003123 unsigned NumProtocols) {
3124 if (NumProtocols == 0) return true;
3125
Douglas Gregor61cc2962012-01-02 02:00:30 +00003126 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3127 return false;
3128
John McCall54e14c42009-10-22 22:37:11 +00003129 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003130 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3131 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003132 return false;
3133 return true;
3134}
3135
3136static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003137 unsigned &NumProtocols) {
3138 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Chris Lattner88cb27a2008-04-07 04:56:42 +00003140 // Sort protocols, keyed by name.
3141 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3142
Douglas Gregor61cc2962012-01-02 02:00:30 +00003143 // Canonicalize.
3144 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3145 Protocols[I] = Protocols[I]->getCanonicalDecl();
3146
Chris Lattner88cb27a2008-04-07 04:56:42 +00003147 // Remove duplicates.
3148 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3149 NumProtocols = ProtocolsEnd-Protocols;
3150}
3151
John McCallc12c5bb2010-05-15 11:32:37 +00003152QualType ASTContext::getObjCObjectType(QualType BaseType,
3153 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003154 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003155 // If the base type is an interface and there aren't any protocols
3156 // to add, then the interface type will do just fine.
3157 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3158 return BaseType;
3159
3160 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003161 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003162 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003163 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003164 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3165 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003166
John McCallc12c5bb2010-05-15 11:32:37 +00003167 // Build the canonical type, which has the canonical base type and
3168 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003169 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003170 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3171 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3172 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003173 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003174 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003175 unsigned UniqueCount = NumProtocols;
3176
John McCall54e14c42009-10-22 22:37:11 +00003177 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003178 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3179 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003180 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003181 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3182 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003183 }
3184
3185 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003186 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3187 }
3188
3189 unsigned Size = sizeof(ObjCObjectTypeImpl);
3190 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3191 void *Mem = Allocate(Size, TypeAlignment);
3192 ObjCObjectTypeImpl *T =
3193 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3194
3195 Types.push_back(T);
3196 ObjCObjectTypes.InsertNode(T, InsertPos);
3197 return QualType(T, 0);
3198}
3199
3200/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3201/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003202QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003203 llvm::FoldingSetNodeID ID;
3204 ObjCObjectPointerType::Profile(ID, ObjectT);
3205
3206 void *InsertPos = 0;
3207 if (ObjCObjectPointerType *QT =
3208 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3209 return QualType(QT, 0);
3210
3211 // Find the canonical object type.
3212 QualType Canonical;
3213 if (!ObjectT.isCanonical()) {
3214 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3215
3216 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003217 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3218 }
3219
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003220 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003221 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3222 ObjCObjectPointerType *QType =
3223 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003224
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003225 Types.push_back(QType);
3226 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003227 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003228}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003229
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003230/// getObjCInterfaceType - Return the unique reference to the type for the
3231/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003232QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3233 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003234 if (Decl->TypeForDecl)
3235 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Douglas Gregor0af55012011-12-16 03:12:41 +00003237 if (PrevDecl) {
3238 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3239 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3240 return QualType(PrevDecl->TypeForDecl, 0);
3241 }
3242
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003243 // Prefer the definition, if there is one.
3244 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3245 Decl = Def;
3246
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003247 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3248 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3249 Decl->TypeForDecl = T;
3250 Types.push_back(T);
3251 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003252}
3253
Douglas Gregor72564e72009-02-26 23:50:07 +00003254/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3255/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003256/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003257/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003258/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003259QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003260 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003261 if (tofExpr->isTypeDependent()) {
3262 llvm::FoldingSetNodeID ID;
3263 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Douglas Gregorb1975722009-07-30 23:18:24 +00003265 void *InsertPos = 0;
3266 DependentTypeOfExprType *Canon
3267 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3268 if (Canon) {
3269 // We already have a "canonical" version of an identical, dependent
3270 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003271 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003272 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003273 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003274 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003275 Canon
3276 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003277 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3278 toe = Canon;
3279 }
3280 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003281 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003282 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003283 }
Steve Naroff9752f252007-08-01 18:02:17 +00003284 Types.push_back(toe);
3285 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003286}
3287
Steve Naroff9752f252007-08-01 18:02:17 +00003288/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3289/// TypeOfType AST's. The only motivation to unique these nodes would be
3290/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003291/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003292/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003293QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003294 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003295 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003296 Types.push_back(tot);
3297 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003298}
3299
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003300
Anders Carlsson395b4752009-06-24 19:06:50 +00003301/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3302/// DecltypeType AST's. The only motivation to unique these nodes would be
3303/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003304/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003305/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003306QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003307 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003308
3309 // C++0x [temp.type]p2:
3310 // If an expression e involves a template parameter, decltype(e) denotes a
3311 // unique dependent type. Two such decltype-specifiers refer to the same
3312 // type only if their expressions are equivalent (14.5.6.1).
3313 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003314 llvm::FoldingSetNodeID ID;
3315 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003317 void *InsertPos = 0;
3318 DependentDecltypeType *Canon
3319 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3320 if (Canon) {
3321 // We already have a "canonical" version of an equivalent, dependent
3322 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003323 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003324 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003325 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003326 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003327 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003328 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3329 dt = Canon;
3330 }
3331 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003332 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3333 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003334 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003335 Types.push_back(dt);
3336 return QualType(dt, 0);
3337}
3338
Sean Huntca63c202011-05-24 22:41:36 +00003339/// getUnaryTransformationType - We don't unique these, since the memory
3340/// savings are minimal and these are rare.
3341QualType ASTContext::getUnaryTransformType(QualType BaseType,
3342 QualType UnderlyingType,
3343 UnaryTransformType::UTTKind Kind)
3344 const {
3345 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003346 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3347 Kind,
3348 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003349 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003350 Types.push_back(Ty);
3351 return QualType(Ty, 0);
3352}
3353
Richard Smith483b9f32011-02-21 20:05:19 +00003354/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003355QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003356 void *InsertPos = 0;
3357 if (!DeducedType.isNull()) {
3358 // Look in the folding set for an existing type.
3359 llvm::FoldingSetNodeID ID;
3360 AutoType::Profile(ID, DeducedType);
3361 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3362 return QualType(AT, 0);
3363 }
3364
3365 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3366 Types.push_back(AT);
3367 if (InsertPos)
3368 AutoTypes.InsertNode(AT, InsertPos);
3369 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003370}
3371
Eli Friedmanb001de72011-10-06 23:00:33 +00003372/// getAtomicType - Return the uniqued reference to the atomic type for
3373/// the given value type.
3374QualType ASTContext::getAtomicType(QualType T) const {
3375 // Unique pointers, to guarantee there is only one pointer of a particular
3376 // structure.
3377 llvm::FoldingSetNodeID ID;
3378 AtomicType::Profile(ID, T);
3379
3380 void *InsertPos = 0;
3381 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3382 return QualType(AT, 0);
3383
3384 // If the atomic value type isn't canonical, this won't be a canonical type
3385 // either, so fill in the canonical type field.
3386 QualType Canonical;
3387 if (!T.isCanonical()) {
3388 Canonical = getAtomicType(getCanonicalType(T));
3389
3390 // Get the new insert position for the node we care about.
3391 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3392 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3393 }
3394 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3395 Types.push_back(New);
3396 AtomicTypes.InsertNode(New, InsertPos);
3397 return QualType(New, 0);
3398}
3399
Richard Smithad762fc2011-04-14 22:09:26 +00003400/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3401QualType ASTContext::getAutoDeductType() const {
3402 if (AutoDeductTy.isNull())
3403 AutoDeductTy = getAutoType(QualType());
3404 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3405 return AutoDeductTy;
3406}
3407
3408/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3409QualType ASTContext::getAutoRRefDeductType() const {
3410 if (AutoRRefDeductTy.isNull())
3411 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3412 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3413 return AutoRRefDeductTy;
3414}
3415
Reid Spencer5f016e22007-07-11 17:01:13 +00003416/// getTagDeclType - Return the unique reference to the type for the
3417/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003418QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003419 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003420 // FIXME: What is the design on getTagDeclType when it requires casting
3421 // away const? mutable?
3422 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003423}
3424
Mike Stump1eb44332009-09-09 15:08:12 +00003425/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3426/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3427/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003428CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003429 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003430}
3431
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003432/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3433CanQualType ASTContext::getIntMaxType() const {
3434 return getFromTargetType(Target->getIntMaxType());
3435}
3436
3437/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3438CanQualType ASTContext::getUIntMaxType() const {
3439 return getFromTargetType(Target->getUIntMaxType());
3440}
3441
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003442/// getSignedWCharType - Return the type of "signed wchar_t".
3443/// Used when in C++, as a GCC extension.
3444QualType ASTContext::getSignedWCharType() const {
3445 // FIXME: derive from "Target" ?
3446 return WCharTy;
3447}
3448
3449/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3450/// Used when in C++, as a GCC extension.
3451QualType ASTContext::getUnsignedWCharType() const {
3452 // FIXME: derive from "Target" ?
3453 return UnsignedIntTy;
3454}
3455
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003456/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003457/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3458QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003459 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003460}
3461
Chris Lattnere6327742008-04-02 05:18:44 +00003462//===----------------------------------------------------------------------===//
3463// Type Operators
3464//===----------------------------------------------------------------------===//
3465
Jay Foad4ba2a172011-01-12 09:06:06 +00003466CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003467 // Push qualifiers into arrays, and then discard any remaining
3468 // qualifiers.
3469 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003470 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003471 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003472 QualType Result;
3473 if (isa<ArrayType>(Ty)) {
3474 Result = getArrayDecayedType(QualType(Ty,0));
3475 } else if (isa<FunctionType>(Ty)) {
3476 Result = getPointerType(QualType(Ty, 0));
3477 } else {
3478 Result = QualType(Ty, 0);
3479 }
3480
3481 return CanQualType::CreateUnsafe(Result);
3482}
3483
John McCall62c28c82011-01-18 07:41:22 +00003484QualType ASTContext::getUnqualifiedArrayType(QualType type,
3485 Qualifiers &quals) {
3486 SplitQualType splitType = type.getSplitUnqualifiedType();
3487
3488 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3489 // the unqualified desugared type and then drops it on the floor.
3490 // We then have to strip that sugar back off with
3491 // getUnqualifiedDesugaredType(), which is silly.
3492 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003493 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003494
3495 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003496 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003497 quals = splitType.Quals;
3498 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003499 }
3500
John McCall62c28c82011-01-18 07:41:22 +00003501 // Otherwise, recurse on the array's element type.
3502 QualType elementType = AT->getElementType();
3503 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3504
3505 // If that didn't change the element type, AT has no qualifiers, so we
3506 // can just use the results in splitType.
3507 if (elementType == unqualElementType) {
3508 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003509 quals = splitType.Quals;
3510 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003511 }
3512
3513 // Otherwise, add in the qualifiers from the outermost type, then
3514 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003515 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003516
Douglas Gregor9dadd942010-05-17 18:45:21 +00003517 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003518 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003519 CAT->getSizeModifier(), 0);
3520 }
3521
Douglas Gregor9dadd942010-05-17 18:45:21 +00003522 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003523 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003524 }
3525
Douglas Gregor9dadd942010-05-17 18:45:21 +00003526 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003527 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003528 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003529 VAT->getSizeModifier(),
3530 VAT->getIndexTypeCVRQualifiers(),
3531 VAT->getBracketsRange());
3532 }
3533
3534 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003535 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003536 DSAT->getSizeModifier(), 0,
3537 SourceRange());
3538}
3539
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003540/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3541/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3542/// they point to and return true. If T1 and T2 aren't pointer types
3543/// or pointer-to-member types, or if they are not similar at this
3544/// level, returns false and leaves T1 and T2 unchanged. Top-level
3545/// qualifiers on T1 and T2 are ignored. This function will typically
3546/// be called in a loop that successively "unwraps" pointer and
3547/// pointer-to-member types to compare them at each level.
3548bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3549 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3550 *T2PtrType = T2->getAs<PointerType>();
3551 if (T1PtrType && T2PtrType) {
3552 T1 = T1PtrType->getPointeeType();
3553 T2 = T2PtrType->getPointeeType();
3554 return true;
3555 }
3556
3557 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3558 *T2MPType = T2->getAs<MemberPointerType>();
3559 if (T1MPType && T2MPType &&
3560 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3561 QualType(T2MPType->getClass(), 0))) {
3562 T1 = T1MPType->getPointeeType();
3563 T2 = T2MPType->getPointeeType();
3564 return true;
3565 }
3566
David Blaikie4e4d0842012-03-11 07:00:24 +00003567 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003568 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3569 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3570 if (T1OPType && T2OPType) {
3571 T1 = T1OPType->getPointeeType();
3572 T2 = T2OPType->getPointeeType();
3573 return true;
3574 }
3575 }
3576
3577 // FIXME: Block pointers, too?
3578
3579 return false;
3580}
3581
Jay Foad4ba2a172011-01-12 09:06:06 +00003582DeclarationNameInfo
3583ASTContext::getNameForTemplate(TemplateName Name,
3584 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003585 switch (Name.getKind()) {
3586 case TemplateName::QualifiedTemplate:
3587 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003588 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003589 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3590 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003591
John McCall14606042011-06-30 08:33:18 +00003592 case TemplateName::OverloadedTemplate: {
3593 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3594 // DNInfo work in progress: CHECKME: what about DNLoc?
3595 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3596 }
3597
3598 case TemplateName::DependentTemplate: {
3599 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003600 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003601 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003602 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3603 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003604 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003605 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3606 // DNInfo work in progress: FIXME: source locations?
3607 DeclarationNameLoc DNLoc;
3608 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3609 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3610 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003611 }
3612 }
3613
John McCall14606042011-06-30 08:33:18 +00003614 case TemplateName::SubstTemplateTemplateParm: {
3615 SubstTemplateTemplateParmStorage *subst
3616 = Name.getAsSubstTemplateTemplateParm();
3617 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3618 NameLoc);
3619 }
3620
3621 case TemplateName::SubstTemplateTemplateParmPack: {
3622 SubstTemplateTemplateParmPackStorage *subst
3623 = Name.getAsSubstTemplateTemplateParmPack();
3624 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3625 NameLoc);
3626 }
3627 }
3628
3629 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003630}
3631
Jay Foad4ba2a172011-01-12 09:06:06 +00003632TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003633 switch (Name.getKind()) {
3634 case TemplateName::QualifiedTemplate:
3635 case TemplateName::Template: {
3636 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003637 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003638 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003639 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3640
3641 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003642 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003643 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003644
John McCall14606042011-06-30 08:33:18 +00003645 case TemplateName::OverloadedTemplate:
3646 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003647
John McCall14606042011-06-30 08:33:18 +00003648 case TemplateName::DependentTemplate: {
3649 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3650 assert(DTN && "Non-dependent template names must refer to template decls.");
3651 return DTN->CanonicalTemplateName;
3652 }
3653
3654 case TemplateName::SubstTemplateTemplateParm: {
3655 SubstTemplateTemplateParmStorage *subst
3656 = Name.getAsSubstTemplateTemplateParm();
3657 return getCanonicalTemplateName(subst->getReplacement());
3658 }
3659
3660 case TemplateName::SubstTemplateTemplateParmPack: {
3661 SubstTemplateTemplateParmPackStorage *subst
3662 = Name.getAsSubstTemplateTemplateParmPack();
3663 TemplateTemplateParmDecl *canonParameter
3664 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3665 TemplateArgument canonArgPack
3666 = getCanonicalTemplateArgument(subst->getArgumentPack());
3667 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3668 }
3669 }
3670
3671 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003672}
3673
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003674bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3675 X = getCanonicalTemplateName(X);
3676 Y = getCanonicalTemplateName(Y);
3677 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3678}
3679
Mike Stump1eb44332009-09-09 15:08:12 +00003680TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003681ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003682 switch (Arg.getKind()) {
3683 case TemplateArgument::Null:
3684 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003685
Douglas Gregor1275ae02009-07-28 23:00:59 +00003686 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003687 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Douglas Gregord2008e22012-04-06 22:40:38 +00003689 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003690 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3691 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003692 }
Mike Stump1eb44332009-09-09 15:08:12 +00003693
Eli Friedmand7a6b162012-09-26 02:36:12 +00003694 case TemplateArgument::NullPtr:
3695 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3696 /*isNullPtr*/true);
3697
Douglas Gregor788cd062009-11-11 01:00:40 +00003698 case TemplateArgument::Template:
3699 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003700
3701 case TemplateArgument::TemplateExpansion:
3702 return TemplateArgument(getCanonicalTemplateName(
3703 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003704 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003705
Douglas Gregor1275ae02009-07-28 23:00:59 +00003706 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003707 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Douglas Gregor1275ae02009-07-28 23:00:59 +00003709 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003710 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Douglas Gregor1275ae02009-07-28 23:00:59 +00003712 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003713 if (Arg.pack_size() == 0)
3714 return Arg;
3715
Douglas Gregor910f8002010-11-07 23:05:16 +00003716 TemplateArgument *CanonArgs
3717 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003718 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003719 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003720 AEnd = Arg.pack_end();
3721 A != AEnd; (void)++A, ++Idx)
3722 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003723
Douglas Gregor910f8002010-11-07 23:05:16 +00003724 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003725 }
3726 }
3727
3728 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003729 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003730}
3731
Douglas Gregord57959a2009-03-27 23:10:48 +00003732NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003733ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003734 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003735 return 0;
3736
3737 switch (NNS->getKind()) {
3738 case NestedNameSpecifier::Identifier:
3739 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003740 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003741 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3742 NNS->getAsIdentifier());
3743
3744 case NestedNameSpecifier::Namespace:
3745 // A namespace is canonical; build a nested-name-specifier with
3746 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003747 return NestedNameSpecifier::Create(*this, 0,
3748 NNS->getAsNamespace()->getOriginalNamespace());
3749
3750 case NestedNameSpecifier::NamespaceAlias:
3751 // A namespace is canonical; build a nested-name-specifier with
3752 // this namespace and no prefix.
3753 return NestedNameSpecifier::Create(*this, 0,
3754 NNS->getAsNamespaceAlias()->getNamespace()
3755 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003756
3757 case NestedNameSpecifier::TypeSpec:
3758 case NestedNameSpecifier::TypeSpecWithTemplate: {
3759 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003760
3761 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3762 // break it apart into its prefix and identifier, then reconsititute those
3763 // as the canonical nested-name-specifier. This is required to canonicalize
3764 // a dependent nested-name-specifier involving typedefs of dependent-name
3765 // types, e.g.,
3766 // typedef typename T::type T1;
3767 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003768 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3769 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003770 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003771
Eli Friedman16412ef2012-03-03 04:09:56 +00003772 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3773 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3774 // first place?
John McCall3b657512011-01-19 10:06:00 +00003775 return NestedNameSpecifier::Create(*this, 0, false,
3776 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003777 }
3778
3779 case NestedNameSpecifier::Global:
3780 // The global specifier is canonical and unique.
3781 return NNS;
3782 }
3783
David Blaikie7530c032012-01-17 06:56:22 +00003784 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003785}
3786
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003787
Jay Foad4ba2a172011-01-12 09:06:06 +00003788const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003789 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003790 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003791 // Handle the common positive case fast.
3792 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3793 return AT;
3794 }
Mike Stump1eb44332009-09-09 15:08:12 +00003795
John McCall0953e762009-09-24 19:53:00 +00003796 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003797 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003798 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003799
John McCall0953e762009-09-24 19:53:00 +00003800 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003801 // implements C99 6.7.3p8: "If the specification of an array type includes
3802 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003803
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003804 // If we get here, we either have type qualifiers on the type, or we have
3805 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003806 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003807
John McCall3b657512011-01-19 10:06:00 +00003808 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003809 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003810
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003811 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003812 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003813 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003814 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003815
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003816 // Otherwise, we have an array and we have qualifiers on it. Push the
3817 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003818 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003819
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003820 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3821 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3822 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003823 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003824 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3825 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3826 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003827 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003828
Mike Stump1eb44332009-09-09 15:08:12 +00003829 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003830 = dyn_cast<DependentSizedArrayType>(ATy))
3831 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003832 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003833 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003834 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003835 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003836 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003837
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003838 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003839 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003840 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003841 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003842 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003843 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003844}
3845
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003846QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003847 // C99 6.7.5.3p7:
3848 // A declaration of a parameter as "array of type" shall be
3849 // adjusted to "qualified pointer to type", where the type
3850 // qualifiers (if any) are those specified within the [ and ] of
3851 // the array type derivation.
3852 if (T->isArrayType())
3853 return getArrayDecayedType(T);
3854
3855 // C99 6.7.5.3p8:
3856 // A declaration of a parameter as "function returning type"
3857 // shall be adjusted to "pointer to function returning type", as
3858 // in 6.3.2.1.
3859 if (T->isFunctionType())
3860 return getPointerType(T);
3861
3862 return T;
3863}
3864
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003865QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003866 T = getVariableArrayDecayedType(T);
3867 T = getAdjustedParameterType(T);
3868 return T.getUnqualifiedType();
3869}
3870
Chris Lattnere6327742008-04-02 05:18:44 +00003871/// getArrayDecayedType - Return the properly qualified result of decaying the
3872/// specified array type to a pointer. This operation is non-trivial when
3873/// handling typedefs etc. The canonical type of "T" must be an array type,
3874/// this returns a pointer to a properly qualified element of the array.
3875///
3876/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003877QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003878 // Get the element type with 'getAsArrayType' so that we don't lose any
3879 // typedefs in the element type of the array. This also handles propagation
3880 // of type qualifiers from the array type into the element type if present
3881 // (C99 6.7.3p8).
3882 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3883 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003885 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003886
3887 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003888 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003889}
3890
John McCall3b657512011-01-19 10:06:00 +00003891QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3892 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003893}
3894
John McCall3b657512011-01-19 10:06:00 +00003895QualType ASTContext::getBaseElementType(QualType type) const {
3896 Qualifiers qs;
3897 while (true) {
3898 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003899 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003900 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003901
John McCall3b657512011-01-19 10:06:00 +00003902 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003903 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003904 }
Mike Stump1eb44332009-09-09 15:08:12 +00003905
John McCall3b657512011-01-19 10:06:00 +00003906 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003907}
3908
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003909/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003910uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003911ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3912 uint64_t ElementCount = 1;
3913 do {
3914 ElementCount *= CA->getSize().getZExtValue();
3915 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3916 } while (CA);
3917 return ElementCount;
3918}
3919
Reid Spencer5f016e22007-07-11 17:01:13 +00003920/// getFloatingRank - Return a relative rank for floating point types.
3921/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003922static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003923 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003924 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003925
John McCall183700f2009-09-21 23:43:11 +00003926 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3927 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003928 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003929 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003930 case BuiltinType::Float: return FloatRank;
3931 case BuiltinType::Double: return DoubleRank;
3932 case BuiltinType::LongDouble: return LongDoubleRank;
3933 }
3934}
3935
Mike Stump1eb44332009-09-09 15:08:12 +00003936/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3937/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003938/// 'typeDomain' is a real floating point or complex type.
3939/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003940QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3941 QualType Domain) const {
3942 FloatingRank EltRank = getFloatingRank(Size);
3943 if (Domain->isComplexType()) {
3944 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003945 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003946 case FloatRank: return FloatComplexTy;
3947 case DoubleRank: return DoubleComplexTy;
3948 case LongDoubleRank: return LongDoubleComplexTy;
3949 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003950 }
Chris Lattner1361b112008-04-06 23:58:54 +00003951
3952 assert(Domain->isRealFloatingType() && "Unknown domain!");
3953 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003954 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003955 case FloatRank: return FloatTy;
3956 case DoubleRank: return DoubleTy;
3957 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003958 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003959 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003960}
3961
Chris Lattner7cfeb082008-04-06 23:55:33 +00003962/// getFloatingTypeOrder - Compare the rank of the two specified floating
3963/// point types, ignoring the domain of the type (i.e. 'double' ==
3964/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003965/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003966int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003967 FloatingRank LHSR = getFloatingRank(LHS);
3968 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Chris Lattnera75cea32008-04-06 23:38:49 +00003970 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003971 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003972 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003973 return 1;
3974 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003975}
3976
Chris Lattnerf52ab252008-04-06 22:59:24 +00003977/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3978/// routine will assert if passed a built-in type that isn't an integer or enum,
3979/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003980unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003981 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003982
Chris Lattnerf52ab252008-04-06 22:59:24 +00003983 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003984 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003985 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003986 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003987 case BuiltinType::Char_S:
3988 case BuiltinType::Char_U:
3989 case BuiltinType::SChar:
3990 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003991 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003992 case BuiltinType::Short:
3993 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003994 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003995 case BuiltinType::Int:
3996 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003997 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003998 case BuiltinType::Long:
3999 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004000 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004001 case BuiltinType::LongLong:
4002 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004003 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004004 case BuiltinType::Int128:
4005 case BuiltinType::UInt128:
4006 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004007 }
4008}
4009
Eli Friedman04e83572009-08-20 04:21:42 +00004010/// \brief Whether this is a promotable bitfield reference according
4011/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4012///
4013/// \returns the type this bit-field will promote to, or NULL if no
4014/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004015QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004016 if (E->isTypeDependent() || E->isValueDependent())
4017 return QualType();
4018
Eli Friedman04e83572009-08-20 04:21:42 +00004019 FieldDecl *Field = E->getBitField();
4020 if (!Field)
4021 return QualType();
4022
4023 QualType FT = Field->getType();
4024
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004025 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004026 uint64_t IntSize = getTypeSize(IntTy);
4027 // GCC extension compatibility: if the bit-field size is less than or equal
4028 // to the size of int, it gets promoted no matter what its type is.
4029 // For instance, unsigned long bf : 4 gets promoted to signed int.
4030 if (BitWidth < IntSize)
4031 return IntTy;
4032
4033 if (BitWidth == IntSize)
4034 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4035
4036 // Types bigger than int are not subject to promotions, and therefore act
4037 // like the base type.
4038 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4039 // is ridiculous.
4040 return QualType();
4041}
4042
Eli Friedmana95d7572009-08-19 07:44:53 +00004043/// getPromotedIntegerType - Returns the type that Promotable will
4044/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4045/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004046QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004047 assert(!Promotable.isNull());
4048 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004049 if (const EnumType *ET = Promotable->getAs<EnumType>())
4050 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004051
4052 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4053 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4054 // (3.9.1) can be converted to a prvalue of the first of the following
4055 // types that can represent all the values of its underlying type:
4056 // int, unsigned int, long int, unsigned long int, long long int, or
4057 // unsigned long long int [...]
4058 // FIXME: Is there some better way to compute this?
4059 if (BT->getKind() == BuiltinType::WChar_S ||
4060 BT->getKind() == BuiltinType::WChar_U ||
4061 BT->getKind() == BuiltinType::Char16 ||
4062 BT->getKind() == BuiltinType::Char32) {
4063 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4064 uint64_t FromSize = getTypeSize(BT);
4065 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4066 LongLongTy, UnsignedLongLongTy };
4067 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4068 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4069 if (FromSize < ToSize ||
4070 (FromSize == ToSize &&
4071 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4072 return PromoteTypes[Idx];
4073 }
4074 llvm_unreachable("char type should fit into long long");
4075 }
4076 }
4077
4078 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004079 if (Promotable->isSignedIntegerType())
4080 return IntTy;
4081 uint64_t PromotableSize = getTypeSize(Promotable);
4082 uint64_t IntSize = getTypeSize(IntTy);
4083 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4084 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4085}
4086
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004087/// \brief Recurses in pointer/array types until it finds an objc retainable
4088/// type and returns its ownership.
4089Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4090 while (!T.isNull()) {
4091 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4092 return T.getObjCLifetime();
4093 if (T->isArrayType())
4094 T = getBaseElementType(T);
4095 else if (const PointerType *PT = T->getAs<PointerType>())
4096 T = PT->getPointeeType();
4097 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004098 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004099 else
4100 break;
4101 }
4102
4103 return Qualifiers::OCL_None;
4104}
4105
Mike Stump1eb44332009-09-09 15:08:12 +00004106/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004107/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004108/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004109int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004110 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4111 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004112 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Chris Lattnerf52ab252008-04-06 22:59:24 +00004114 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4115 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Chris Lattner7cfeb082008-04-06 23:55:33 +00004117 unsigned LHSRank = getIntegerRank(LHSC);
4118 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004119
Chris Lattner7cfeb082008-04-06 23:55:33 +00004120 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4121 if (LHSRank == RHSRank) return 0;
4122 return LHSRank > RHSRank ? 1 : -1;
4123 }
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Chris Lattner7cfeb082008-04-06 23:55:33 +00004125 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4126 if (LHSUnsigned) {
4127 // If the unsigned [LHS] type is larger, return it.
4128 if (LHSRank >= RHSRank)
4129 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004130
Chris Lattner7cfeb082008-04-06 23:55:33 +00004131 // If the signed type can represent all values of the unsigned type, it
4132 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004133 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004134 return -1;
4135 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004136
Chris Lattner7cfeb082008-04-06 23:55:33 +00004137 // If the unsigned [RHS] type is larger, return it.
4138 if (RHSRank >= LHSRank)
4139 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Chris Lattner7cfeb082008-04-06 23:55:33 +00004141 // If the signed type can represent all values of the unsigned type, it
4142 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004143 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004144 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004145}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004146
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004147static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004148CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4149 DeclContext *DC, IdentifierInfo *Id) {
4150 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004151 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004152 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004153 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004154 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004155}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004156
Mike Stump1eb44332009-09-09 15:08:12 +00004157// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004158QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004159 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004160 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004161 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004162 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004163 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004164
Anders Carlssonf06273f2007-11-19 00:25:30 +00004165 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Anders Carlsson71993dd2007-08-17 05:31:46 +00004167 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004168 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004169 // int flags;
4170 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004171 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004172 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004173 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004174 FieldTypes[3] = LongTy;
4175
Anders Carlsson71993dd2007-08-17 05:31:46 +00004176 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004177 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004178 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004179 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004180 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004181 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004182 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004183 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004184 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004185 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004186 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004187 }
4188
Douglas Gregor838db382010-02-11 01:19:42 +00004189 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004190 }
Mike Stump1eb44332009-09-09 15:08:12 +00004191
Anders Carlsson71993dd2007-08-17 05:31:46 +00004192 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004193}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004194
Douglas Gregor319ac892009-04-23 22:29:11 +00004195void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004196 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004197 assert(Rec && "Invalid CFConstantStringType");
4198 CFConstantStringTypeDecl = Rec->getDecl();
4199}
4200
Jay Foad4ba2a172011-01-12 09:06:06 +00004201QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004202 if (BlockDescriptorType)
4203 return getTagDeclType(BlockDescriptorType);
4204
4205 RecordDecl *T;
4206 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004207 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004208 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004209 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004210
4211 QualType FieldTypes[] = {
4212 UnsignedLongTy,
4213 UnsignedLongTy,
4214 };
4215
4216 const char *FieldNames[] = {
4217 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004218 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004219 };
4220
4221 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004222 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004223 SourceLocation(),
4224 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004225 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004226 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004227 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004228 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004229 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004230 T->addDecl(Field);
4231 }
4232
Douglas Gregor838db382010-02-11 01:19:42 +00004233 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004234
4235 BlockDescriptorType = T;
4236
4237 return getTagDeclType(BlockDescriptorType);
4238}
4239
Jay Foad4ba2a172011-01-12 09:06:06 +00004240QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004241 if (BlockDescriptorExtendedType)
4242 return getTagDeclType(BlockDescriptorExtendedType);
4243
4244 RecordDecl *T;
4245 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004246 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004247 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004248 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004249
4250 QualType FieldTypes[] = {
4251 UnsignedLongTy,
4252 UnsignedLongTy,
4253 getPointerType(VoidPtrTy),
4254 getPointerType(VoidPtrTy)
4255 };
4256
4257 const char *FieldNames[] = {
4258 "reserved",
4259 "Size",
4260 "CopyFuncPtr",
4261 "DestroyFuncPtr"
4262 };
4263
4264 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004265 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004266 SourceLocation(),
4267 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004268 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004269 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004270 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004271 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004272 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004273 T->addDecl(Field);
4274 }
4275
Douglas Gregor838db382010-02-11 01:19:42 +00004276 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004277
4278 BlockDescriptorExtendedType = T;
4279
4280 return getTagDeclType(BlockDescriptorExtendedType);
4281}
4282
Jay Foad4ba2a172011-01-12 09:06:06 +00004283bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00004284 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004285 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00004286 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004287 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4288 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00004289 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004290
4291 }
4292 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004293 return false;
4294}
4295
Jay Foad4ba2a172011-01-12 09:06:06 +00004296QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00004297ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004298 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00004299 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004300 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00004301 // unsigned int __flags;
4302 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00004303 // void *__copy_helper; // as needed
4304 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004305 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00004306 // } *
4307
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004308 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4309
4310 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004311 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00004312 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4313 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004314 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004315 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004316 T->startDefinition();
4317 QualType Int32Ty = IntTy;
4318 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4319 QualType FieldTypes[] = {
4320 getPointerType(VoidPtrTy),
4321 getPointerType(getTagDeclType(T)),
4322 Int32Ty,
4323 Int32Ty,
4324 getPointerType(VoidPtrTy),
4325 getPointerType(VoidPtrTy),
4326 Ty
4327 };
4328
Chris Lattner5f9e2722011-07-23 10:55:15 +00004329 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004330 "__isa",
4331 "__forwarding",
4332 "__flags",
4333 "__size",
4334 "__copy_helper",
4335 "__destroy_helper",
4336 DeclName,
4337 };
4338
4339 for (size_t i = 0; i < 7; ++i) {
4340 if (!HasCopyAndDispose && i >=4 && i <= 5)
4341 continue;
4342 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004343 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004344 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004345 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004346 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004347 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004348 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004349 T->addDecl(Field);
4350 }
4351
Douglas Gregor838db382010-02-11 01:19:42 +00004352 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004353
4354 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004355}
4356
Douglas Gregore97179c2011-09-08 01:46:34 +00004357TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4358 if (!ObjCInstanceTypeDecl)
4359 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4360 getTranslationUnitDecl(),
4361 SourceLocation(),
4362 SourceLocation(),
4363 &Idents.get("instancetype"),
4364 getTrivialTypeSourceInfo(getObjCIdType()));
4365 return ObjCInstanceTypeDecl;
4366}
4367
Anders Carlssone8c49532007-10-29 06:33:42 +00004368// This returns true if a type has been typedefed to BOOL:
4369// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004370static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004371 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004372 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4373 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004374
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004375 return false;
4376}
4377
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004378/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004379/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004380CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004381 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4382 return CharUnits::Zero();
4383
Ken Dyck199c3d62010-01-11 17:06:35 +00004384 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004386 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004387 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004388 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004389 // Treat arrays as pointers, since that's how they're passed in.
4390 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004391 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004392 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004393}
4394
4395static inline
4396std::string charUnitsToString(const CharUnits &CU) {
4397 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004398}
4399
John McCall6b5a61b2011-02-07 10:33:21 +00004400/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004401/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004402std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4403 std::string S;
4404
David Chisnall5e530af2009-11-17 19:33:30 +00004405 const BlockDecl *Decl = Expr->getBlockDecl();
4406 QualType BlockTy =
4407 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4408 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004409 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004410 // Compute size of all parameters.
4411 // Start with computing size of a pointer in number of bytes.
4412 // FIXME: There might(should) be a better way of doing this computation!
4413 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004414 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4415 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004416 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004417 E = Decl->param_end(); PI != E; ++PI) {
4418 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004419 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004420 if (sz.isZero())
4421 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004422 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004423 ParmOffset += sz;
4424 }
4425 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004426 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004427 // Block pointer and offset.
4428 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004429
4430 // Argument types.
4431 ParmOffset = PtrSize;
4432 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4433 Decl->param_end(); PI != E; ++PI) {
4434 ParmVarDecl *PVDecl = *PI;
4435 QualType PType = PVDecl->getOriginalType();
4436 if (const ArrayType *AT =
4437 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4438 // Use array's original type only if it has known number of
4439 // elements.
4440 if (!isa<ConstantArrayType>(AT))
4441 PType = PVDecl->getType();
4442 } else if (PType->isFunctionType())
4443 PType = PVDecl->getType();
4444 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004445 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004446 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004447 }
John McCall6b5a61b2011-02-07 10:33:21 +00004448
4449 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004450}
4451
Douglas Gregorf968d832011-05-27 01:19:52 +00004452bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004453 std::string& S) {
4454 // Encode result type.
4455 getObjCEncodingForType(Decl->getResultType(), S);
4456 CharUnits ParmOffset;
4457 // Compute size of all parameters.
4458 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4459 E = Decl->param_end(); PI != E; ++PI) {
4460 QualType PType = (*PI)->getType();
4461 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004462 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004463 continue;
4464
David Chisnall5389f482010-12-30 14:05:53 +00004465 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004466 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004467 ParmOffset += sz;
4468 }
4469 S += charUnitsToString(ParmOffset);
4470 ParmOffset = CharUnits::Zero();
4471
4472 // Argument types.
4473 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4474 E = Decl->param_end(); PI != E; ++PI) {
4475 ParmVarDecl *PVDecl = *PI;
4476 QualType PType = PVDecl->getOriginalType();
4477 if (const ArrayType *AT =
4478 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4479 // Use array's original type only if it has known number of
4480 // elements.
4481 if (!isa<ConstantArrayType>(AT))
4482 PType = PVDecl->getType();
4483 } else if (PType->isFunctionType())
4484 PType = PVDecl->getType();
4485 getObjCEncodingForType(PType, S);
4486 S += charUnitsToString(ParmOffset);
4487 ParmOffset += getObjCEncodingTypeSize(PType);
4488 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004489
4490 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004491}
4492
Bob Wilsondc8dab62011-11-30 01:57:58 +00004493/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4494/// method parameter or return type. If Extended, include class names and
4495/// block object types.
4496void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4497 QualType T, std::string& S,
4498 bool Extended) const {
4499 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4500 getObjCEncodingForTypeQualifier(QT, S);
4501 // Encode parameter type.
4502 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4503 true /*OutermostType*/,
4504 false /*EncodingProperty*/,
4505 false /*StructField*/,
4506 Extended /*EncodeBlockParameters*/,
4507 Extended /*EncodeClassNames*/);
4508}
4509
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004510/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004511/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004512bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004513 std::string& S,
4514 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004515 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004516 // Encode return type.
4517 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4518 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004519 // Compute size of all parameters.
4520 // Start with computing size of a pointer in number of bytes.
4521 // FIXME: There might(should) be a better way of doing this computation!
4522 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004523 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004524 // The first two arguments (self and _cmd) are pointers; account for
4525 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004526 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004527 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004528 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004529 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004530 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004531 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004532 continue;
4533
Ken Dyck199c3d62010-01-11 17:06:35 +00004534 assert (sz.isPositive() &&
4535 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004536 ParmOffset += sz;
4537 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004538 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004539 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004540 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004541
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004542 // Argument types.
4543 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004544 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004545 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004546 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004547 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004548 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004549 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4550 // Use array's original type only if it has known number of
4551 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004552 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004553 PType = PVDecl->getType();
4554 } else if (PType->isFunctionType())
4555 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004556 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4557 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004558 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004559 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004560 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004561
4562 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004563}
4564
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004565/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004566/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004567/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4568/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004569/// Property attributes are stored as a comma-delimited C string. The simple
4570/// attributes readonly and bycopy are encoded as single characters. The
4571/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4572/// encoded as single characters, followed by an identifier. Property types
4573/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004574/// these attributes are defined by the following enumeration:
4575/// @code
4576/// enum PropertyAttributes {
4577/// kPropertyReadOnly = 'R', // property is read-only.
4578/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4579/// kPropertyByref = '&', // property is a reference to the value last assigned
4580/// kPropertyDynamic = 'D', // property is dynamic
4581/// kPropertyGetter = 'G', // followed by getter selector name
4582/// kPropertySetter = 'S', // followed by setter selector name
4583/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004584/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004585/// kPropertyWeak = 'W' // 'weak' property
4586/// kPropertyStrong = 'P' // property GC'able
4587/// kPropertyNonAtomic = 'N' // property non-atomic
4588/// };
4589/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004590void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004591 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004592 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004593 // Collect information from the property implementation decl(s).
4594 bool Dynamic = false;
4595 ObjCPropertyImplDecl *SynthesizePID = 0;
4596
4597 // FIXME: Duplicated code due to poor abstraction.
4598 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004599 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004600 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4601 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004602 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004603 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004604 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004605 if (PID->getPropertyDecl() == PD) {
4606 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4607 Dynamic = true;
4608 } else {
4609 SynthesizePID = PID;
4610 }
4611 }
4612 }
4613 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004614 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004615 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004616 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004617 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004618 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004619 if (PID->getPropertyDecl() == PD) {
4620 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4621 Dynamic = true;
4622 } else {
4623 SynthesizePID = PID;
4624 }
4625 }
Mike Stump1eb44332009-09-09 15:08:12 +00004626 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004627 }
4628 }
4629
4630 // FIXME: This is not very efficient.
4631 S = "T";
4632
4633 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004634 // GCC has some special rules regarding encoding of properties which
4635 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004636 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004637 true /* outermost type */,
4638 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004639
4640 if (PD->isReadOnly()) {
4641 S += ",R";
4642 } else {
4643 switch (PD->getSetterKind()) {
4644 case ObjCPropertyDecl::Assign: break;
4645 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004646 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004647 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004648 }
4649 }
4650
4651 // It really isn't clear at all what this means, since properties
4652 // are "dynamic by default".
4653 if (Dynamic)
4654 S += ",D";
4655
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004656 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4657 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004658
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004659 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4660 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004661 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004662 }
4663
4664 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4665 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004666 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004667 }
4668
4669 if (SynthesizePID) {
4670 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4671 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004672 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004673 }
4674
4675 // FIXME: OBJCGC: weak & strong
4676}
4677
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004678/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004679/// Another legacy compatibility encoding: 32-bit longs are encoded as
4680/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004681/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4682///
4683void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004684 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004685 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004686 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004687 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004688 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004689 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004690 PointeeTy = IntTy;
4691 }
4692 }
4693}
4694
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004695void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004696 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004697 // We follow the behavior of gcc, expanding structures which are
4698 // directly pointed to, and expanding embedded structures. Note that
4699 // these rules are sufficient to prevent recursive encoding of the
4700 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004701 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004702 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004703}
4704
David Chisnall64fd7e82010-06-04 01:10:52 +00004705static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4706 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004707 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004708 case BuiltinType::Void: return 'v';
4709 case BuiltinType::Bool: return 'B';
4710 case BuiltinType::Char_U:
4711 case BuiltinType::UChar: return 'C';
4712 case BuiltinType::UShort: return 'S';
4713 case BuiltinType::UInt: return 'I';
4714 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004715 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004716 case BuiltinType::UInt128: return 'T';
4717 case BuiltinType::ULongLong: return 'Q';
4718 case BuiltinType::Char_S:
4719 case BuiltinType::SChar: return 'c';
4720 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004721 case BuiltinType::WChar_S:
4722 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004723 case BuiltinType::Int: return 'i';
4724 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004725 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004726 case BuiltinType::LongLong: return 'q';
4727 case BuiltinType::Int128: return 't';
4728 case BuiltinType::Float: return 'f';
4729 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004730 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004731 }
4732}
4733
Douglas Gregor5471bc82011-09-08 17:18:35 +00004734static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4735 EnumDecl *Enum = ET->getDecl();
4736
4737 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4738 if (!Enum->isFixed())
4739 return 'i';
4740
4741 // The encoding of a fixed enum type matches its fixed underlying type.
4742 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4743}
4744
Jay Foad4ba2a172011-01-12 09:06:06 +00004745static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004746 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004747 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004748 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004749 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4750 // The GNU runtime requires more information; bitfields are encoded as b,
4751 // then the offset (in bits) of the first element, then the type of the
4752 // bitfield, then the size in bits. For example, in this structure:
4753 //
4754 // struct
4755 // {
4756 // int integer;
4757 // int flags:2;
4758 // };
4759 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4760 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4761 // information is not especially sensible, but we're stuck with it for
4762 // compatibility with GCC, although providing it breaks anything that
4763 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004764 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004765 const RecordDecl *RD = FD->getParent();
4766 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004767 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004768 if (const EnumType *ET = T->getAs<EnumType>())
4769 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004770 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004771 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004772 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004773 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004774}
4775
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004776// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004777void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4778 bool ExpandPointedToStructures,
4779 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004780 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004781 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004782 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004783 bool StructField,
4784 bool EncodeBlockParameters,
4785 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004786 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004787 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004788 return EncodeBitField(this, S, T, FD);
4789 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004790 return;
4791 }
Mike Stump1eb44332009-09-09 15:08:12 +00004792
John McCall183700f2009-09-21 23:43:11 +00004793 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004794 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004795 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004796 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004797 return;
4798 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004799
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004800 // encoding for pointer or r3eference types.
4801 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004802 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004803 if (PT->isObjCSelType()) {
4804 S += ':';
4805 return;
4806 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004807 PointeeTy = PT->getPointeeType();
4808 }
4809 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4810 PointeeTy = RT->getPointeeType();
4811 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004812 bool isReadOnly = false;
4813 // For historical/compatibility reasons, the read-only qualifier of the
4814 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4815 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004816 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004817 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004818 if (OutermostType && T.isConstQualified()) {
4819 isReadOnly = true;
4820 S += 'r';
4821 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004822 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004823 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004824 while (P->getAs<PointerType>())
4825 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004826 if (P.isConstQualified()) {
4827 isReadOnly = true;
4828 S += 'r';
4829 }
4830 }
4831 if (isReadOnly) {
4832 // Another legacy compatibility encoding. Some ObjC qualifier and type
4833 // combinations need to be rearranged.
4834 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004835 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004836 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004837 }
Mike Stump1eb44332009-09-09 15:08:12 +00004838
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004839 if (PointeeTy->isCharType()) {
4840 // char pointer types should be encoded as '*' unless it is a
4841 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004842 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004843 S += '*';
4844 return;
4845 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004846 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004847 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4848 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4849 S += '#';
4850 return;
4851 }
4852 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4853 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4854 S += '@';
4855 return;
4856 }
4857 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004858 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004859 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004860 getLegacyIntegralTypeEncoding(PointeeTy);
4861
Mike Stump1eb44332009-09-09 15:08:12 +00004862 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004863 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004864 return;
4865 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004866
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004867 if (const ArrayType *AT =
4868 // Ignore type qualifiers etc.
4869 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004870 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004871 // Incomplete arrays are encoded as a pointer to the array element.
4872 S += '^';
4873
Mike Stump1eb44332009-09-09 15:08:12 +00004874 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004875 false, ExpandStructures, FD);
4876 } else {
4877 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004878
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004879 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4880 if (getTypeSize(CAT->getElementType()) == 0)
4881 S += '0';
4882 else
4883 S += llvm::utostr(CAT->getSize().getZExtValue());
4884 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004885 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004886 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4887 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004888 S += '0';
4889 }
Mike Stump1eb44332009-09-09 15:08:12 +00004890
4891 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004892 false, ExpandStructures, FD);
4893 S += ']';
4894 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004895 return;
4896 }
Mike Stump1eb44332009-09-09 15:08:12 +00004897
John McCall183700f2009-09-21 23:43:11 +00004898 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004899 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004900 return;
4901 }
Mike Stump1eb44332009-09-09 15:08:12 +00004902
Ted Kremenek6217b802009-07-29 21:53:49 +00004903 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004904 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004905 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004906 // Anonymous structures print as '?'
4907 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4908 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004909 if (ClassTemplateSpecializationDecl *Spec
4910 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4911 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4912 std::string TemplateArgsStr
4913 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004914 TemplateArgs.data(),
4915 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004916 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004917
4918 S += TemplateArgsStr;
4919 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004920 } else {
4921 S += '?';
4922 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004923 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004924 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004925 if (!RDecl->isUnion()) {
4926 getObjCEncodingForStructureImpl(RDecl, S, FD);
4927 } else {
4928 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4929 FieldEnd = RDecl->field_end();
4930 Field != FieldEnd; ++Field) {
4931 if (FD) {
4932 S += '"';
4933 S += Field->getNameAsString();
4934 S += '"';
4935 }
Mike Stump1eb44332009-09-09 15:08:12 +00004936
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004937 // Special case bit-fields.
4938 if (Field->isBitField()) {
4939 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00004940 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004941 } else {
4942 QualType qt = Field->getType();
4943 getLegacyIntegralTypeEncoding(qt);
4944 getObjCEncodingForTypeImpl(qt, S, false, true,
4945 FD, /*OutermostType*/false,
4946 /*EncodingProperty*/false,
4947 /*StructField*/true);
4948 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004949 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004950 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004951 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004952 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004953 return;
4954 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004955
Douglas Gregor5471bc82011-09-08 17:18:35 +00004956 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004957 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004958 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004959 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004960 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004961 return;
4962 }
Mike Stump1eb44332009-09-09 15:08:12 +00004963
Bob Wilsondc8dab62011-11-30 01:57:58 +00004964 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004965 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004966 if (EncodeBlockParameters) {
4967 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4968
4969 S += '<';
4970 // Block return type
4971 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4972 ExpandPointedToStructures, ExpandStructures,
4973 FD,
4974 false /* OutermostType */,
4975 EncodingProperty,
4976 false /* StructField */,
4977 EncodeBlockParameters,
4978 EncodeClassNames);
4979 // Block self
4980 S += "@?";
4981 // Block parameters
4982 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4983 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4984 E = FPT->arg_type_end(); I && (I != E); ++I) {
4985 getObjCEncodingForTypeImpl(*I, S,
4986 ExpandPointedToStructures,
4987 ExpandStructures,
4988 FD,
4989 false /* OutermostType */,
4990 EncodingProperty,
4991 false /* StructField */,
4992 EncodeBlockParameters,
4993 EncodeClassNames);
4994 }
4995 }
4996 S += '>';
4997 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004998 return;
4999 }
Mike Stump1eb44332009-09-09 15:08:12 +00005000
John McCallc12c5bb2010-05-15 11:32:37 +00005001 // Ignore protocol qualifiers when mangling at this level.
5002 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
5003 T = OT->getBaseType();
5004
John McCall0953e762009-09-24 19:53:00 +00005005 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005006 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005007 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005008 S += '{';
5009 const IdentifierInfo *II = OI->getIdentifier();
5010 S += II->getName();
5011 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005012 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005013 DeepCollectObjCIvars(OI, true, Ivars);
5014 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005015 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005016 if (Field->isBitField())
5017 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005018 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005019 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005020 }
5021 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005022 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005023 }
Mike Stump1eb44332009-09-09 15:08:12 +00005024
John McCall183700f2009-09-21 23:43:11 +00005025 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00005026 if (OPT->isObjCIdType()) {
5027 S += '@';
5028 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005029 }
Mike Stump1eb44332009-09-09 15:08:12 +00005030
Steve Naroff27d20a22009-10-28 22:03:49 +00005031 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5032 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5033 // Since this is a binary compatibility issue, need to consult with runtime
5034 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005035 S += '#';
5036 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005037 }
Mike Stump1eb44332009-09-09 15:08:12 +00005038
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005039 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005040 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005041 ExpandPointedToStructures,
5042 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005043 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005044 // Note that we do extended encoding of protocol qualifer list
5045 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005046 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005047 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5048 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005049 S += '<';
5050 S += (*I)->getNameAsString();
5051 S += '>';
5052 }
5053 S += '"';
5054 }
5055 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005056 }
Mike Stump1eb44332009-09-09 15:08:12 +00005057
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005058 QualType PointeeTy = OPT->getPointeeType();
5059 if (!EncodingProperty &&
5060 isa<TypedefType>(PointeeTy.getTypePtr())) {
5061 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005062 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005063 // {...};
5064 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005065 getObjCEncodingForTypeImpl(PointeeTy, S,
5066 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005067 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00005068 return;
5069 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005070
5071 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005072 if (OPT->getInterfaceDecl() &&
5073 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005074 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005075 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005076 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5077 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005078 S += '<';
5079 S += (*I)->getNameAsString();
5080 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005081 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005082 S += '"';
5083 }
5084 return;
5085 }
Mike Stump1eb44332009-09-09 15:08:12 +00005086
John McCall532ec7b2010-05-17 23:56:34 +00005087 // gcc just blithely ignores member pointers.
5088 // TODO: maybe there should be a mangling for these
5089 if (T->getAs<MemberPointerType>())
5090 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005091
5092 if (T->isVectorType()) {
5093 // This matches gcc's encoding, even though technically it is
5094 // insufficient.
5095 // FIXME. We should do a better job than gcc.
5096 return;
5097 }
5098
David Blaikieb219cfc2011-09-23 05:06:16 +00005099 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005100}
5101
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005102void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5103 std::string &S,
5104 const FieldDecl *FD,
5105 bool includeVBases) const {
5106 assert(RDecl && "Expected non-null RecordDecl");
5107 assert(!RDecl->isUnion() && "Should not be called for unions");
5108 if (!RDecl->getDefinition())
5109 return;
5110
5111 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5112 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5113 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5114
5115 if (CXXRec) {
5116 for (CXXRecordDecl::base_class_iterator
5117 BI = CXXRec->bases_begin(),
5118 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5119 if (!BI->isVirtual()) {
5120 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005121 if (base->isEmpty())
5122 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005123 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005124 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5125 std::make_pair(offs, base));
5126 }
5127 }
5128 }
5129
5130 unsigned i = 0;
5131 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5132 FieldEnd = RDecl->field_end();
5133 Field != FieldEnd; ++Field, ++i) {
5134 uint64_t offs = layout.getFieldOffset(i);
5135 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005136 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005137 }
5138
5139 if (CXXRec && includeVBases) {
5140 for (CXXRecordDecl::base_class_iterator
5141 BI = CXXRec->vbases_begin(),
5142 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5143 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005144 if (base->isEmpty())
5145 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005146 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005147 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5148 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5149 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005150 }
5151 }
5152
5153 CharUnits size;
5154 if (CXXRec) {
5155 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5156 } else {
5157 size = layout.getSize();
5158 }
5159
5160 uint64_t CurOffs = 0;
5161 std::multimap<uint64_t, NamedDecl *>::iterator
5162 CurLayObj = FieldOrBaseOffsets.begin();
5163
Douglas Gregor58db7a52012-04-27 22:30:01 +00005164 if (CXXRec && CXXRec->isDynamicClass() &&
5165 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005166 if (FD) {
5167 S += "\"_vptr$";
5168 std::string recname = CXXRec->getNameAsString();
5169 if (recname.empty()) recname = "?";
5170 S += recname;
5171 S += '"';
5172 }
5173 S += "^^?";
5174 CurOffs += getTypeSize(VoidPtrTy);
5175 }
5176
5177 if (!RDecl->hasFlexibleArrayMember()) {
5178 // Mark the end of the structure.
5179 uint64_t offs = toBits(size);
5180 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5181 std::make_pair(offs, (NamedDecl*)0));
5182 }
5183
5184 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5185 assert(CurOffs <= CurLayObj->first);
5186
5187 if (CurOffs < CurLayObj->first) {
5188 uint64_t padding = CurLayObj->first - CurOffs;
5189 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5190 // packing/alignment of members is different that normal, in which case
5191 // the encoding will be out-of-sync with the real layout.
5192 // If the runtime switches to just consider the size of types without
5193 // taking into account alignment, we could make padding explicit in the
5194 // encoding (e.g. using arrays of chars). The encoding strings would be
5195 // longer then though.
5196 CurOffs += padding;
5197 }
5198
5199 NamedDecl *dcl = CurLayObj->second;
5200 if (dcl == 0)
5201 break; // reached end of structure.
5202
5203 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5204 // We expand the bases without their virtual bases since those are going
5205 // in the initial structure. Note that this differs from gcc which
5206 // expands virtual bases each time one is encountered in the hierarchy,
5207 // making the encoding type bigger than it really is.
5208 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005209 assert(!base->isEmpty());
5210 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005211 } else {
5212 FieldDecl *field = cast<FieldDecl>(dcl);
5213 if (FD) {
5214 S += '"';
5215 S += field->getNameAsString();
5216 S += '"';
5217 }
5218
5219 if (field->isBitField()) {
5220 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005221 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005222 } else {
5223 QualType qt = field->getType();
5224 getLegacyIntegralTypeEncoding(qt);
5225 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5226 /*OutermostType*/false,
5227 /*EncodingProperty*/false,
5228 /*StructField*/true);
5229 CurOffs += getTypeSize(field->getType());
5230 }
5231 }
5232 }
5233}
5234
Mike Stump1eb44332009-09-09 15:08:12 +00005235void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005236 std::string& S) const {
5237 if (QT & Decl::OBJC_TQ_In)
5238 S += 'n';
5239 if (QT & Decl::OBJC_TQ_Inout)
5240 S += 'N';
5241 if (QT & Decl::OBJC_TQ_Out)
5242 S += 'o';
5243 if (QT & Decl::OBJC_TQ_Bycopy)
5244 S += 'O';
5245 if (QT & Decl::OBJC_TQ_Byref)
5246 S += 'R';
5247 if (QT & Decl::OBJC_TQ_Oneway)
5248 S += 'V';
5249}
5250
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005251TypedefDecl *ASTContext::getObjCIdDecl() const {
5252 if (!ObjCIdDecl) {
5253 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5254 T = getObjCObjectPointerType(T);
5255 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5256 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5257 getTranslationUnitDecl(),
5258 SourceLocation(), SourceLocation(),
5259 &Idents.get("id"), IdInfo);
5260 }
5261
5262 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005263}
5264
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005265TypedefDecl *ASTContext::getObjCSelDecl() const {
5266 if (!ObjCSelDecl) {
5267 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5268 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5269 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5270 getTranslationUnitDecl(),
5271 SourceLocation(), SourceLocation(),
5272 &Idents.get("SEL"), SelInfo);
5273 }
5274 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005275}
5276
Douglas Gregor79d67262011-08-12 05:59:41 +00005277TypedefDecl *ASTContext::getObjCClassDecl() const {
5278 if (!ObjCClassDecl) {
5279 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5280 T = getObjCObjectPointerType(T);
5281 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5282 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5283 getTranslationUnitDecl(),
5284 SourceLocation(), SourceLocation(),
5285 &Idents.get("Class"), ClassInfo);
5286 }
5287
5288 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005289}
5290
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005291ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5292 if (!ObjCProtocolClassDecl) {
5293 ObjCProtocolClassDecl
5294 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5295 SourceLocation(),
5296 &Idents.get("Protocol"),
5297 /*PrevDecl=*/0,
5298 SourceLocation(), true);
5299 }
5300
5301 return ObjCProtocolClassDecl;
5302}
5303
Meador Ingec5613b22012-06-16 03:34:49 +00005304//===----------------------------------------------------------------------===//
5305// __builtin_va_list Construction Functions
5306//===----------------------------------------------------------------------===//
5307
5308static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5309 // typedef char* __builtin_va_list;
5310 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5311 TypeSourceInfo *TInfo
5312 = Context->getTrivialTypeSourceInfo(CharPtrType);
5313
5314 TypedefDecl *VaListTypeDecl
5315 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5316 Context->getTranslationUnitDecl(),
5317 SourceLocation(), SourceLocation(),
5318 &Context->Idents.get("__builtin_va_list"),
5319 TInfo);
5320 return VaListTypeDecl;
5321}
5322
5323static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5324 // typedef void* __builtin_va_list;
5325 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5326 TypeSourceInfo *TInfo
5327 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5328
5329 TypedefDecl *VaListTypeDecl
5330 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5331 Context->getTranslationUnitDecl(),
5332 SourceLocation(), SourceLocation(),
5333 &Context->Idents.get("__builtin_va_list"),
5334 TInfo);
5335 return VaListTypeDecl;
5336}
5337
5338static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5339 // typedef struct __va_list_tag {
5340 RecordDecl *VaListTagDecl;
5341
5342 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5343 Context->getTranslationUnitDecl(),
5344 &Context->Idents.get("__va_list_tag"));
5345 VaListTagDecl->startDefinition();
5346
5347 const size_t NumFields = 5;
5348 QualType FieldTypes[NumFields];
5349 const char *FieldNames[NumFields];
5350
5351 // unsigned char gpr;
5352 FieldTypes[0] = Context->UnsignedCharTy;
5353 FieldNames[0] = "gpr";
5354
5355 // unsigned char fpr;
5356 FieldTypes[1] = Context->UnsignedCharTy;
5357 FieldNames[1] = "fpr";
5358
5359 // unsigned short reserved;
5360 FieldTypes[2] = Context->UnsignedShortTy;
5361 FieldNames[2] = "reserved";
5362
5363 // void* overflow_arg_area;
5364 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5365 FieldNames[3] = "overflow_arg_area";
5366
5367 // void* reg_save_area;
5368 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5369 FieldNames[4] = "reg_save_area";
5370
5371 // Create fields
5372 for (unsigned i = 0; i < NumFields; ++i) {
5373 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5374 SourceLocation(),
5375 SourceLocation(),
5376 &Context->Idents.get(FieldNames[i]),
5377 FieldTypes[i], /*TInfo=*/0,
5378 /*BitWidth=*/0,
5379 /*Mutable=*/false,
5380 ICIS_NoInit);
5381 Field->setAccess(AS_public);
5382 VaListTagDecl->addDecl(Field);
5383 }
5384 VaListTagDecl->completeDefinition();
5385 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005386 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005387
5388 // } __va_list_tag;
5389 TypedefDecl *VaListTagTypedefDecl
5390 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5391 Context->getTranslationUnitDecl(),
5392 SourceLocation(), SourceLocation(),
5393 &Context->Idents.get("__va_list_tag"),
5394 Context->getTrivialTypeSourceInfo(VaListTagType));
5395 QualType VaListTagTypedefType =
5396 Context->getTypedefType(VaListTagTypedefDecl);
5397
5398 // typedef __va_list_tag __builtin_va_list[1];
5399 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5400 QualType VaListTagArrayType
5401 = Context->getConstantArrayType(VaListTagTypedefType,
5402 Size, ArrayType::Normal, 0);
5403 TypeSourceInfo *TInfo
5404 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5405 TypedefDecl *VaListTypedefDecl
5406 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5407 Context->getTranslationUnitDecl(),
5408 SourceLocation(), SourceLocation(),
5409 &Context->Idents.get("__builtin_va_list"),
5410 TInfo);
5411
5412 return VaListTypedefDecl;
5413}
5414
5415static TypedefDecl *
5416CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5417 // typedef struct __va_list_tag {
5418 RecordDecl *VaListTagDecl;
5419 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5420 Context->getTranslationUnitDecl(),
5421 &Context->Idents.get("__va_list_tag"));
5422 VaListTagDecl->startDefinition();
5423
5424 const size_t NumFields = 4;
5425 QualType FieldTypes[NumFields];
5426 const char *FieldNames[NumFields];
5427
5428 // unsigned gp_offset;
5429 FieldTypes[0] = Context->UnsignedIntTy;
5430 FieldNames[0] = "gp_offset";
5431
5432 // unsigned fp_offset;
5433 FieldTypes[1] = Context->UnsignedIntTy;
5434 FieldNames[1] = "fp_offset";
5435
5436 // void* overflow_arg_area;
5437 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5438 FieldNames[2] = "overflow_arg_area";
5439
5440 // void* reg_save_area;
5441 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5442 FieldNames[3] = "reg_save_area";
5443
5444 // Create fields
5445 for (unsigned i = 0; i < NumFields; ++i) {
5446 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5447 VaListTagDecl,
5448 SourceLocation(),
5449 SourceLocation(),
5450 &Context->Idents.get(FieldNames[i]),
5451 FieldTypes[i], /*TInfo=*/0,
5452 /*BitWidth=*/0,
5453 /*Mutable=*/false,
5454 ICIS_NoInit);
5455 Field->setAccess(AS_public);
5456 VaListTagDecl->addDecl(Field);
5457 }
5458 VaListTagDecl->completeDefinition();
5459 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005460 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005461
5462 // } __va_list_tag;
5463 TypedefDecl *VaListTagTypedefDecl
5464 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5465 Context->getTranslationUnitDecl(),
5466 SourceLocation(), SourceLocation(),
5467 &Context->Idents.get("__va_list_tag"),
5468 Context->getTrivialTypeSourceInfo(VaListTagType));
5469 QualType VaListTagTypedefType =
5470 Context->getTypedefType(VaListTagTypedefDecl);
5471
5472 // typedef __va_list_tag __builtin_va_list[1];
5473 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5474 QualType VaListTagArrayType
5475 = Context->getConstantArrayType(VaListTagTypedefType,
5476 Size, ArrayType::Normal,0);
5477 TypeSourceInfo *TInfo
5478 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5479 TypedefDecl *VaListTypedefDecl
5480 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5481 Context->getTranslationUnitDecl(),
5482 SourceLocation(), SourceLocation(),
5483 &Context->Idents.get("__builtin_va_list"),
5484 TInfo);
5485
5486 return VaListTypedefDecl;
5487}
5488
5489static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5490 // typedef int __builtin_va_list[4];
5491 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5492 QualType IntArrayType
5493 = Context->getConstantArrayType(Context->IntTy,
5494 Size, ArrayType::Normal, 0);
5495 TypedefDecl *VaListTypedefDecl
5496 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5497 Context->getTranslationUnitDecl(),
5498 SourceLocation(), SourceLocation(),
5499 &Context->Idents.get("__builtin_va_list"),
5500 Context->getTrivialTypeSourceInfo(IntArrayType));
5501
5502 return VaListTypedefDecl;
5503}
5504
5505static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5506 TargetInfo::BuiltinVaListKind Kind) {
5507 switch (Kind) {
5508 case TargetInfo::CharPtrBuiltinVaList:
5509 return CreateCharPtrBuiltinVaListDecl(Context);
5510 case TargetInfo::VoidPtrBuiltinVaList:
5511 return CreateVoidPtrBuiltinVaListDecl(Context);
5512 case TargetInfo::PowerABIBuiltinVaList:
5513 return CreatePowerABIBuiltinVaListDecl(Context);
5514 case TargetInfo::X86_64ABIBuiltinVaList:
5515 return CreateX86_64ABIBuiltinVaListDecl(Context);
5516 case TargetInfo::PNaClABIBuiltinVaList:
5517 return CreatePNaClABIBuiltinVaListDecl(Context);
5518 }
5519
5520 llvm_unreachable("Unhandled __builtin_va_list type kind");
5521}
5522
5523TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5524 if (!BuiltinVaListDecl)
5525 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5526
5527 return BuiltinVaListDecl;
5528}
5529
Meador Ingefb40e3f2012-07-01 15:57:25 +00005530QualType ASTContext::getVaListTagType() const {
5531 // Force the creation of VaListTagTy by building the __builtin_va_list
5532 // declaration.
5533 if (VaListTagTy.isNull())
5534 (void) getBuiltinVaListDecl();
5535
5536 return VaListTagTy;
5537}
5538
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005539void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005540 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005541 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005542
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005543 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005544}
5545
John McCall0bd6feb2009-12-02 08:04:21 +00005546/// \brief Retrieve the template name that corresponds to a non-empty
5547/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005548TemplateName
5549ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5550 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005551 unsigned size = End - Begin;
5552 assert(size > 1 && "set is not overloaded!");
5553
5554 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5555 size * sizeof(FunctionTemplateDecl*));
5556 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5557
5558 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005559 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005560 NamedDecl *D = *I;
5561 assert(isa<FunctionTemplateDecl>(D) ||
5562 (isa<UsingShadowDecl>(D) &&
5563 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5564 *Storage++ = D;
5565 }
5566
5567 return TemplateName(OT);
5568}
5569
Douglas Gregor7532dc62009-03-30 22:58:21 +00005570/// \brief Retrieve the template name that represents a qualified
5571/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005572TemplateName
5573ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5574 bool TemplateKeyword,
5575 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005576 assert(NNS && "Missing nested-name-specifier in qualified template name");
5577
Douglas Gregor789b1f62010-02-04 18:10:26 +00005578 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005579 llvm::FoldingSetNodeID ID;
5580 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5581
5582 void *InsertPos = 0;
5583 QualifiedTemplateName *QTN =
5584 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5585 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005586 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5587 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005588 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5589 }
5590
5591 return TemplateName(QTN);
5592}
5593
5594/// \brief Retrieve the template name that represents a dependent
5595/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005596TemplateName
5597ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5598 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005599 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005600 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005601
5602 llvm::FoldingSetNodeID ID;
5603 DependentTemplateName::Profile(ID, NNS, Name);
5604
5605 void *InsertPos = 0;
5606 DependentTemplateName *QTN =
5607 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5608
5609 if (QTN)
5610 return TemplateName(QTN);
5611
5612 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5613 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005614 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5615 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005616 } else {
5617 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00005618 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5619 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005620 DependentTemplateName *CheckQTN =
5621 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5622 assert(!CheckQTN && "Dependent type name canonicalization broken");
5623 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005624 }
5625
5626 DependentTemplateNames.InsertNode(QTN, InsertPos);
5627 return TemplateName(QTN);
5628}
5629
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005630/// \brief Retrieve the template name that represents a dependent
5631/// template name such as \c MetaFun::template operator+.
5632TemplateName
5633ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005634 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005635 assert((!NNS || NNS->isDependent()) &&
5636 "Nested name specifier must be dependent");
5637
5638 llvm::FoldingSetNodeID ID;
5639 DependentTemplateName::Profile(ID, NNS, Operator);
5640
5641 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005642 DependentTemplateName *QTN
5643 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005644
5645 if (QTN)
5646 return TemplateName(QTN);
5647
5648 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5649 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005650 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5651 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005652 } else {
5653 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00005654 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5655 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005656
5657 DependentTemplateName *CheckQTN
5658 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5659 assert(!CheckQTN && "Dependent template name canonicalization broken");
5660 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005661 }
5662
5663 DependentTemplateNames.InsertNode(QTN, InsertPos);
5664 return TemplateName(QTN);
5665}
5666
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005667TemplateName
John McCall14606042011-06-30 08:33:18 +00005668ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5669 TemplateName replacement) const {
5670 llvm::FoldingSetNodeID ID;
5671 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5672
5673 void *insertPos = 0;
5674 SubstTemplateTemplateParmStorage *subst
5675 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5676
5677 if (!subst) {
5678 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5679 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5680 }
5681
5682 return TemplateName(subst);
5683}
5684
5685TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005686ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5687 const TemplateArgument &ArgPack) const {
5688 ASTContext &Self = const_cast<ASTContext &>(*this);
5689 llvm::FoldingSetNodeID ID;
5690 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5691
5692 void *InsertPos = 0;
5693 SubstTemplateTemplateParmPackStorage *Subst
5694 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5695
5696 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005697 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005698 ArgPack.pack_size(),
5699 ArgPack.pack_begin());
5700 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5701 }
5702
5703 return TemplateName(Subst);
5704}
5705
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005706/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005707/// TargetInfo, produce the corresponding type. The unsigned @p Type
5708/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005709CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005710 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005711 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005712 case TargetInfo::SignedShort: return ShortTy;
5713 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5714 case TargetInfo::SignedInt: return IntTy;
5715 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5716 case TargetInfo::SignedLong: return LongTy;
5717 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5718 case TargetInfo::SignedLongLong: return LongLongTy;
5719 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5720 }
5721
David Blaikieb219cfc2011-09-23 05:06:16 +00005722 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005723}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005724
5725//===----------------------------------------------------------------------===//
5726// Type Predicates.
5727//===----------------------------------------------------------------------===//
5728
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005729/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5730/// garbage collection attribute.
5731///
John McCallae278a32011-01-12 00:34:59 +00005732Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005733 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005734 return Qualifiers::GCNone;
5735
David Blaikie4e4d0842012-03-11 07:00:24 +00005736 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005737 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5738
5739 // Default behaviour under objective-C's gc is for ObjC pointers
5740 // (or pointers to them) be treated as though they were declared
5741 // as __strong.
5742 if (GCAttrs == Qualifiers::GCNone) {
5743 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5744 return Qualifiers::Strong;
5745 else if (Ty->isPointerType())
5746 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5747 } else {
5748 // It's not valid to set GC attributes on anything that isn't a
5749 // pointer.
5750#ifndef NDEBUG
5751 QualType CT = Ty->getCanonicalTypeInternal();
5752 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5753 CT = AT->getElementType();
5754 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5755#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005756 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005757 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005758}
5759
Chris Lattner6ac46a42008-04-07 06:51:04 +00005760//===----------------------------------------------------------------------===//
5761// Type Compatibility Testing
5762//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005763
Mike Stump1eb44332009-09-09 15:08:12 +00005764/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005765/// compatible.
5766static bool areCompatVectorTypes(const VectorType *LHS,
5767 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005768 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005769 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005770 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005771}
5772
Douglas Gregor255210e2010-08-06 10:14:59 +00005773bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5774 QualType SecondVec) {
5775 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5776 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5777
5778 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5779 return true;
5780
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005781 // Treat Neon vector types and most AltiVec vector types as if they are the
5782 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005783 const VectorType *First = FirstVec->getAs<VectorType>();
5784 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005785 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005786 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005787 First->getVectorKind() != VectorType::AltiVecPixel &&
5788 First->getVectorKind() != VectorType::AltiVecBool &&
5789 Second->getVectorKind() != VectorType::AltiVecPixel &&
5790 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005791 return true;
5792
5793 return false;
5794}
5795
Steve Naroff4084c302009-07-23 01:01:38 +00005796//===----------------------------------------------------------------------===//
5797// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5798//===----------------------------------------------------------------------===//
5799
5800/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5801/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005802bool
5803ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5804 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005805 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005806 return true;
5807 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5808 E = rProto->protocol_end(); PI != E; ++PI)
5809 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5810 return true;
5811 return false;
5812}
5813
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00005814/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00005815/// return true if lhs's protocols conform to rhs's protocol; false
5816/// otherwise.
5817bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5818 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5819 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5820 return false;
5821}
5822
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00005823/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5824/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005825bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5826 QualType rhs) {
5827 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5828 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5829 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5830
5831 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5832 E = lhsQID->qual_end(); I != E; ++I) {
5833 bool match = false;
5834 ObjCProtocolDecl *lhsProto = *I;
5835 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5836 E = rhsOPT->qual_end(); J != E; ++J) {
5837 ObjCProtocolDecl *rhsProto = *J;
5838 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5839 match = true;
5840 break;
5841 }
5842 }
5843 if (!match)
5844 return false;
5845 }
5846 return true;
5847}
5848
Steve Naroff4084c302009-07-23 01:01:38 +00005849/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5850/// ObjCQualifiedIDType.
5851bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5852 bool compare) {
5853 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005854 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005855 lhs->isObjCIdType() || lhs->isObjCClassType())
5856 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005857 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005858 rhs->isObjCIdType() || rhs->isObjCClassType())
5859 return true;
5860
5861 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005862 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005863
Steve Naroff4084c302009-07-23 01:01:38 +00005864 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005865
Steve Naroff4084c302009-07-23 01:01:38 +00005866 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005867 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005868 // make sure we check the class hierarchy.
5869 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5870 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5871 E = lhsQID->qual_end(); I != E; ++I) {
5872 // when comparing an id<P> on lhs with a static type on rhs,
5873 // see if static class implements all of id's protocols, directly or
5874 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005875 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005876 return false;
5877 }
5878 }
5879 // If there are no qualifiers and no interface, we have an 'id'.
5880 return true;
5881 }
Mike Stump1eb44332009-09-09 15:08:12 +00005882 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005883 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5884 E = lhsQID->qual_end(); I != E; ++I) {
5885 ObjCProtocolDecl *lhsProto = *I;
5886 bool match = false;
5887
5888 // when comparing an id<P> on lhs with a static type on rhs,
5889 // see if static class implements all of id's protocols, directly or
5890 // through its super class and categories.
5891 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5892 E = rhsOPT->qual_end(); J != E; ++J) {
5893 ObjCProtocolDecl *rhsProto = *J;
5894 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5895 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5896 match = true;
5897 break;
5898 }
5899 }
Mike Stump1eb44332009-09-09 15:08:12 +00005900 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005901 // make sure we check the class hierarchy.
5902 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5903 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5904 E = lhsQID->qual_end(); I != E; ++I) {
5905 // when comparing an id<P> on lhs with a static type on rhs,
5906 // see if static class implements all of id's protocols, directly or
5907 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005908 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005909 match = true;
5910 break;
5911 }
5912 }
5913 }
5914 if (!match)
5915 return false;
5916 }
Mike Stump1eb44332009-09-09 15:08:12 +00005917
Steve Naroff4084c302009-07-23 01:01:38 +00005918 return true;
5919 }
Mike Stump1eb44332009-09-09 15:08:12 +00005920
Steve Naroff4084c302009-07-23 01:01:38 +00005921 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5922 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5923
Mike Stump1eb44332009-09-09 15:08:12 +00005924 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005925 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005926 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005927 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5928 E = lhsOPT->qual_end(); I != E; ++I) {
5929 ObjCProtocolDecl *lhsProto = *I;
5930 bool match = false;
5931
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005932 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005933 // see if static class implements all of id's protocols, directly or
5934 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005935 // First, lhs protocols in the qualifier list must be found, direct
5936 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005937 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5938 E = rhsQID->qual_end(); J != E; ++J) {
5939 ObjCProtocolDecl *rhsProto = *J;
5940 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5941 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5942 match = true;
5943 break;
5944 }
5945 }
5946 if (!match)
5947 return false;
5948 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005949
5950 // Static class's protocols, or its super class or category protocols
5951 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5952 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5953 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5954 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5955 // This is rather dubious but matches gcc's behavior. If lhs has
5956 // no type qualifier and its class has no static protocol(s)
5957 // assume that it is mismatch.
5958 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5959 return false;
5960 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5961 LHSInheritedProtocols.begin(),
5962 E = LHSInheritedProtocols.end(); I != E; ++I) {
5963 bool match = false;
5964 ObjCProtocolDecl *lhsProto = (*I);
5965 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5966 E = rhsQID->qual_end(); J != E; ++J) {
5967 ObjCProtocolDecl *rhsProto = *J;
5968 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5969 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5970 match = true;
5971 break;
5972 }
5973 }
5974 if (!match)
5975 return false;
5976 }
5977 }
Steve Naroff4084c302009-07-23 01:01:38 +00005978 return true;
5979 }
5980 return false;
5981}
5982
Eli Friedman3d815e72008-08-22 00:56:42 +00005983/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005984/// compatible for assignment from RHS to LHS. This handles validation of any
5985/// protocol qualifiers on the LHS or RHS.
5986///
Steve Naroff14108da2009-07-10 23:34:53 +00005987bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5988 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005989 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5990 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5991
Steve Naroffde2e22d2009-07-15 18:40:39 +00005992 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005993 if (LHS->isObjCUnqualifiedIdOrClass() ||
5994 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005995 return true;
5996
John McCallc12c5bb2010-05-15 11:32:37 +00005997 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005998 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5999 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006000 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006001
6002 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6003 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6004 QualType(RHSOPT,0));
6005
John McCallc12c5bb2010-05-15 11:32:37 +00006006 // If we have 2 user-defined types, fall into that path.
6007 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006008 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006009
Steve Naroff4084c302009-07-23 01:01:38 +00006010 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006011}
6012
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006013/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006014/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006015/// arguments in block literals. When passed as arguments, passing 'A*' where
6016/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6017/// not OK. For the return type, the opposite is not OK.
6018bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6019 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006020 const ObjCObjectPointerType *RHSOPT,
6021 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006022 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006023 return true;
6024
6025 if (LHSOPT->isObjCBuiltinType()) {
6026 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6027 }
6028
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006029 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006030 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6031 QualType(RHSOPT,0),
6032 false);
6033
6034 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6035 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6036 if (LHS && RHS) { // We have 2 user-defined types.
6037 if (LHS != RHS) {
6038 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006039 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006040 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006041 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006042 }
6043 else
6044 return true;
6045 }
6046 return false;
6047}
6048
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006049/// getIntersectionOfProtocols - This routine finds the intersection of set
6050/// of protocols inherited from two distinct objective-c pointer objects.
6051/// It is used to build composite qualifier list of the composite type of
6052/// the conditional expression involving two objective-c pointer objects.
6053static
6054void getIntersectionOfProtocols(ASTContext &Context,
6055 const ObjCObjectPointerType *LHSOPT,
6056 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006057 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006058
John McCallc12c5bb2010-05-15 11:32:37 +00006059 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6060 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6061 assert(LHS->getInterface() && "LHS must have an interface base");
6062 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006063
6064 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6065 unsigned LHSNumProtocols = LHS->getNumProtocols();
6066 if (LHSNumProtocols > 0)
6067 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6068 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006069 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006070 Context.CollectInheritedProtocols(LHS->getInterface(),
6071 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006072 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6073 LHSInheritedProtocols.end());
6074 }
6075
6076 unsigned RHSNumProtocols = RHS->getNumProtocols();
6077 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006078 ObjCProtocolDecl **RHSProtocols =
6079 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006080 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6081 if (InheritedProtocolSet.count(RHSProtocols[i]))
6082 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006083 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006084 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006085 Context.CollectInheritedProtocols(RHS->getInterface(),
6086 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006087 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6088 RHSInheritedProtocols.begin(),
6089 E = RHSInheritedProtocols.end(); I != E; ++I)
6090 if (InheritedProtocolSet.count((*I)))
6091 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006092 }
6093}
6094
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006095/// areCommonBaseCompatible - Returns common base class of the two classes if
6096/// one found. Note that this is O'2 algorithm. But it will be called as the
6097/// last type comparison in a ?-exp of ObjC pointer types before a
6098/// warning is issued. So, its invokation is extremely rare.
6099QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006100 const ObjCObjectPointerType *Lptr,
6101 const ObjCObjectPointerType *Rptr) {
6102 const ObjCObjectType *LHS = Lptr->getObjectType();
6103 const ObjCObjectType *RHS = Rptr->getObjectType();
6104 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6105 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006106 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006107 return QualType();
6108
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006109 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006110 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006111 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006112 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006113 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6114
6115 QualType Result = QualType(LHS, 0);
6116 if (!Protocols.empty())
6117 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6118 Result = getObjCObjectPointerType(Result);
6119 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006120 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006121 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006122
6123 return QualType();
6124}
6125
John McCallc12c5bb2010-05-15 11:32:37 +00006126bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6127 const ObjCObjectType *RHS) {
6128 assert(LHS->getInterface() && "LHS is not an interface type");
6129 assert(RHS->getInterface() && "RHS is not an interface type");
6130
Chris Lattner6ac46a42008-04-07 06:51:04 +00006131 // Verify that the base decls are compatible: the RHS must be a subclass of
6132 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006133 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006134 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006135
Chris Lattner6ac46a42008-04-07 06:51:04 +00006136 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6137 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006138 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006139 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006140
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006141 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6142 // more detailed analysis is required.
6143 if (RHS->getNumProtocols() == 0) {
6144 // OK, if LHS is a superclass of RHS *and*
6145 // this superclass is assignment compatible with LHS.
6146 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006147 bool IsSuperClass =
6148 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6149 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006150 // OK if conversion of LHS to SuperClass results in narrowing of types
6151 // ; i.e., SuperClass may implement at least one of the protocols
6152 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6153 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6154 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006155 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006156 // If super class has no protocols, it is not a match.
6157 if (SuperClassInheritedProtocols.empty())
6158 return false;
6159
6160 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6161 LHSPE = LHS->qual_end();
6162 LHSPI != LHSPE; LHSPI++) {
6163 bool SuperImplementsProtocol = false;
6164 ObjCProtocolDecl *LHSProto = (*LHSPI);
6165
6166 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6167 SuperClassInheritedProtocols.begin(),
6168 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6169 ObjCProtocolDecl *SuperClassProto = (*I);
6170 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6171 SuperImplementsProtocol = true;
6172 break;
6173 }
6174 }
6175 if (!SuperImplementsProtocol)
6176 return false;
6177 }
6178 return true;
6179 }
6180 return false;
6181 }
Mike Stump1eb44332009-09-09 15:08:12 +00006182
John McCallc12c5bb2010-05-15 11:32:37 +00006183 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6184 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006185 LHSPI != LHSPE; LHSPI++) {
6186 bool RHSImplementsProtocol = false;
6187
6188 // If the RHS doesn't implement the protocol on the left, the types
6189 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006190 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6191 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006192 RHSPI != RHSPE; RHSPI++) {
6193 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006194 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006195 break;
6196 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006197 }
6198 // FIXME: For better diagnostics, consider passing back the protocol name.
6199 if (!RHSImplementsProtocol)
6200 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006201 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006202 // The RHS implements all protocols listed on the LHS.
6203 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006204}
6205
Steve Naroff389bf462009-02-12 17:52:19 +00006206bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6207 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006208 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6209 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006210
Steve Naroff14108da2009-07-10 23:34:53 +00006211 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006212 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006213
6214 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6215 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006216}
6217
Douglas Gregor569c3162010-08-07 11:51:51 +00006218bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6219 return canAssignObjCInterfaces(
6220 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6221 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6222}
6223
Mike Stump1eb44332009-09-09 15:08:12 +00006224/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006225/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006226/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006227/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006228bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6229 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006230 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006231 return hasSameType(LHS, RHS);
6232
Douglas Gregor447234d2010-07-29 15:18:02 +00006233 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006234}
6235
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006236bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006237 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006238}
6239
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006240bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6241 return !mergeTypes(LHS, RHS, true).isNull();
6242}
6243
Peter Collingbourne48466752010-10-24 18:30:18 +00006244/// mergeTransparentUnionType - if T is a transparent union type and a member
6245/// of T is compatible with SubType, return the merged type, else return
6246/// QualType()
6247QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6248 bool OfBlockPointer,
6249 bool Unqualified) {
6250 if (const RecordType *UT = T->getAsUnionType()) {
6251 RecordDecl *UD = UT->getDecl();
6252 if (UD->hasAttr<TransparentUnionAttr>()) {
6253 for (RecordDecl::field_iterator it = UD->field_begin(),
6254 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006255 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006256 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6257 if (!MT.isNull())
6258 return MT;
6259 }
6260 }
6261 }
6262
6263 return QualType();
6264}
6265
6266/// mergeFunctionArgumentTypes - merge two types which appear as function
6267/// argument types
6268QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6269 bool OfBlockPointer,
6270 bool Unqualified) {
6271 // GNU extension: two types are compatible if they appear as a function
6272 // argument, one of the types is a transparent union type and the other
6273 // type is compatible with a union member
6274 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6275 Unqualified);
6276 if (!lmerge.isNull())
6277 return lmerge;
6278
6279 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6280 Unqualified);
6281 if (!rmerge.isNull())
6282 return rmerge;
6283
6284 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6285}
6286
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006287QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006288 bool OfBlockPointer,
6289 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006290 const FunctionType *lbase = lhs->getAs<FunctionType>();
6291 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006292 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6293 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006294 bool allLTypes = true;
6295 bool allRTypes = true;
6296
6297 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006298 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006299 if (OfBlockPointer) {
6300 QualType RHS = rbase->getResultType();
6301 QualType LHS = lbase->getResultType();
6302 bool UnqualifiedResult = Unqualified;
6303 if (!UnqualifiedResult)
6304 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006305 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006306 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006307 else
John McCall8cc246c2010-12-15 01:06:38 +00006308 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6309 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006310 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006311
6312 if (Unqualified)
6313 retType = retType.getUnqualifiedType();
6314
6315 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6316 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6317 if (Unqualified) {
6318 LRetType = LRetType.getUnqualifiedType();
6319 RRetType = RRetType.getUnqualifiedType();
6320 }
6321
6322 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006323 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006324 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006325 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006326
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006327 // FIXME: double check this
6328 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6329 // rbase->getRegParmAttr() != 0 &&
6330 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006331 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6332 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006333
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006334 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006335 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006336 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006337
John McCall8cc246c2010-12-15 01:06:38 +00006338 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006339 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6340 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006341 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6342 return QualType();
6343
John McCallf85e1932011-06-15 23:02:42 +00006344 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6345 return QualType();
6346
Fariborz Jahanian53c81672011-10-05 00:05:34 +00006347 // functypes which return are preferred over those that do not.
6348 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6349 allLTypes = false;
6350 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6351 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006352 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6353 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006354
John McCallf85e1932011-06-15 23:02:42 +00006355 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006356
Eli Friedman3d815e72008-08-22 00:56:42 +00006357 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006358 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6359 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006360 unsigned lproto_nargs = lproto->getNumArgs();
6361 unsigned rproto_nargs = rproto->getNumArgs();
6362
6363 // Compatible functions must have the same number of arguments
6364 if (lproto_nargs != rproto_nargs)
6365 return QualType();
6366
6367 // Variadic and non-variadic functions aren't compatible
6368 if (lproto->isVariadic() != rproto->isVariadic())
6369 return QualType();
6370
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006371 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6372 return QualType();
6373
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006374 if (LangOpts.ObjCAutoRefCount &&
6375 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6376 return QualType();
6377
Eli Friedman3d815e72008-08-22 00:56:42 +00006378 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006379 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006380 for (unsigned i = 0; i < lproto_nargs; i++) {
6381 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6382 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006383 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6384 OfBlockPointer,
6385 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006386 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006387
6388 if (Unqualified)
6389 argtype = argtype.getUnqualifiedType();
6390
Eli Friedman3d815e72008-08-22 00:56:42 +00006391 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006392 if (Unqualified) {
6393 largtype = largtype.getUnqualifiedType();
6394 rargtype = rargtype.getUnqualifiedType();
6395 }
6396
Chris Lattner61710852008-10-05 17:34:18 +00006397 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6398 allLTypes = false;
6399 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6400 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006401 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006402
Eli Friedman3d815e72008-08-22 00:56:42 +00006403 if (allLTypes) return lhs;
6404 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006405
6406 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6407 EPI.ExtInfo = einfo;
6408 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006409 }
6410
6411 if (lproto) allRTypes = false;
6412 if (rproto) allLTypes = false;
6413
Douglas Gregor72564e72009-02-26 23:50:07 +00006414 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006415 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006416 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006417 if (proto->isVariadic()) return QualType();
6418 // Check that the types are compatible with the types that
6419 // would result from default argument promotions (C99 6.7.5.3p15).
6420 // The only types actually affected are promotable integer
6421 // types and floats, which would be passed as a different
6422 // type depending on whether the prototype is visible.
6423 unsigned proto_nargs = proto->getNumArgs();
6424 for (unsigned i = 0; i < proto_nargs; ++i) {
6425 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006426
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006427 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006428 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006429 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6430 argTy = Enum->getDecl()->getIntegerType();
6431 if (argTy.isNull())
6432 return QualType();
6433 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006434
Eli Friedman3d815e72008-08-22 00:56:42 +00006435 if (argTy->isPromotableIntegerType() ||
6436 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6437 return QualType();
6438 }
6439
6440 if (allLTypes) return lhs;
6441 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006442
6443 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6444 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006445 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006446 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006447 }
6448
6449 if (allLTypes) return lhs;
6450 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006451 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006452}
6453
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006454QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006455 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006456 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006457 // C++ [expr]: If an expression initially has the type "reference to T", the
6458 // type is adjusted to "T" prior to any further analysis, the expression
6459 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006460 // expression is an lvalue unless the reference is an rvalue reference and
6461 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006462 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6463 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006464
6465 if (Unqualified) {
6466 LHS = LHS.getUnqualifiedType();
6467 RHS = RHS.getUnqualifiedType();
6468 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006469
Eli Friedman3d815e72008-08-22 00:56:42 +00006470 QualType LHSCan = getCanonicalType(LHS),
6471 RHSCan = getCanonicalType(RHS);
6472
6473 // If two types are identical, they are compatible.
6474 if (LHSCan == RHSCan)
6475 return LHS;
6476
John McCall0953e762009-09-24 19:53:00 +00006477 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006478 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6479 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006480 if (LQuals != RQuals) {
6481 // If any of these qualifiers are different, we have a type
6482 // mismatch.
6483 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006484 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6485 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006486 return QualType();
6487
6488 // Exactly one GC qualifier difference is allowed: __strong is
6489 // okay if the other type has no GC qualifier but is an Objective
6490 // C object pointer (i.e. implicitly strong by default). We fix
6491 // this by pretending that the unqualified type was actually
6492 // qualified __strong.
6493 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6494 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6495 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6496
6497 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6498 return QualType();
6499
6500 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6501 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6502 }
6503 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6504 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6505 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006506 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006507 }
6508
6509 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006510
Eli Friedman852d63b2009-06-01 01:22:52 +00006511 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6512 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006513
Chris Lattner1adb8832008-01-14 05:45:46 +00006514 // We want to consider the two function types to be the same for these
6515 // comparisons, just force one to the other.
6516 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6517 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006518
6519 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006520 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6521 LHSClass = Type::ConstantArray;
6522 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6523 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006524
John McCallc12c5bb2010-05-15 11:32:37 +00006525 // ObjCInterfaces are just specialized ObjCObjects.
6526 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6527 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6528
Nate Begeman213541a2008-04-18 23:10:10 +00006529 // Canonicalize ExtVector -> Vector.
6530 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6531 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006532
Chris Lattnera36a61f2008-04-07 05:43:21 +00006533 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006534 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006535 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006536 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006537 // Compatibility is based on the underlying type, not the promotion
6538 // type.
John McCall183700f2009-09-21 23:43:11 +00006539 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006540 QualType TINT = ETy->getDecl()->getIntegerType();
6541 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006542 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006543 }
John McCall183700f2009-09-21 23:43:11 +00006544 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006545 QualType TINT = ETy->getDecl()->getIntegerType();
6546 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006547 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006548 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006549 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006550 if (OfBlockPointer && !BlockReturnType) {
6551 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6552 return LHS;
6553 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6554 return RHS;
6555 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006556
Eli Friedman3d815e72008-08-22 00:56:42 +00006557 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006558 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006559
Steve Naroff4a746782008-01-09 22:43:08 +00006560 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006561 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006562#define TYPE(Class, Base)
6563#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006564#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006565#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6566#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6567#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006568 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006569
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006570 case Type::LValueReference:
6571 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006572 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006573 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006574
John McCallc12c5bb2010-05-15 11:32:37 +00006575 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006576 case Type::IncompleteArray:
6577 case Type::VariableArray:
6578 case Type::FunctionProto:
6579 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006580 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006581
Chris Lattner1adb8832008-01-14 05:45:46 +00006582 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006583 {
6584 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006585 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6586 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006587 if (Unqualified) {
6588 LHSPointee = LHSPointee.getUnqualifiedType();
6589 RHSPointee = RHSPointee.getUnqualifiedType();
6590 }
6591 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6592 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006593 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006594 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006595 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006596 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006597 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006598 return getPointerType(ResultType);
6599 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006600 case Type::BlockPointer:
6601 {
6602 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006603 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6604 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006605 if (Unqualified) {
6606 LHSPointee = LHSPointee.getUnqualifiedType();
6607 RHSPointee = RHSPointee.getUnqualifiedType();
6608 }
6609 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6610 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006611 if (ResultType.isNull()) return QualType();
6612 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6613 return LHS;
6614 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6615 return RHS;
6616 return getBlockPointerType(ResultType);
6617 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006618 case Type::Atomic:
6619 {
6620 // Merge two pointer types, while trying to preserve typedef info
6621 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6622 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6623 if (Unqualified) {
6624 LHSValue = LHSValue.getUnqualifiedType();
6625 RHSValue = RHSValue.getUnqualifiedType();
6626 }
6627 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6628 Unqualified);
6629 if (ResultType.isNull()) return QualType();
6630 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6631 return LHS;
6632 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6633 return RHS;
6634 return getAtomicType(ResultType);
6635 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006636 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006637 {
6638 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6639 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6640 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6641 return QualType();
6642
6643 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6644 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006645 if (Unqualified) {
6646 LHSElem = LHSElem.getUnqualifiedType();
6647 RHSElem = RHSElem.getUnqualifiedType();
6648 }
6649
6650 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006651 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006652 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6653 return LHS;
6654 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6655 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006656 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6657 ArrayType::ArraySizeModifier(), 0);
6658 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6659 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006660 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6661 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006662 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6663 return LHS;
6664 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6665 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006666 if (LVAT) {
6667 // FIXME: This isn't correct! But tricky to implement because
6668 // the array's size has to be the size of LHS, but the type
6669 // has to be different.
6670 return LHS;
6671 }
6672 if (RVAT) {
6673 // FIXME: This isn't correct! But tricky to implement because
6674 // the array's size has to be the size of RHS, but the type
6675 // has to be different.
6676 return RHS;
6677 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006678 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6679 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006680 return getIncompleteArrayType(ResultType,
6681 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006682 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006683 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006684 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006685 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006686 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006687 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006688 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006689 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006690 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006691 case Type::Complex:
6692 // Distinct complex types are incompatible.
6693 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006694 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006695 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006696 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6697 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006698 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006699 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006700 case Type::ObjCObject: {
6701 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006702 // FIXME: This should be type compatibility, e.g. whether
6703 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006704 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6705 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6706 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006707 return LHS;
6708
Eli Friedman3d815e72008-08-22 00:56:42 +00006709 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006710 }
Steve Naroff14108da2009-07-10 23:34:53 +00006711 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006712 if (OfBlockPointer) {
6713 if (canAssignObjCInterfacesInBlockPointer(
6714 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006715 RHS->getAs<ObjCObjectPointerType>(),
6716 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006717 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006718 return QualType();
6719 }
John McCall183700f2009-09-21 23:43:11 +00006720 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6721 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006722 return LHS;
6723
Steve Naroffbc76dd02008-12-10 22:14:21 +00006724 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006725 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006726 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006727
David Blaikie7530c032012-01-17 06:56:22 +00006728 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006729}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006730
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006731bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6732 const FunctionProtoType *FromFunctionType,
6733 const FunctionProtoType *ToFunctionType) {
6734 if (FromFunctionType->hasAnyConsumedArgs() !=
6735 ToFunctionType->hasAnyConsumedArgs())
6736 return false;
6737 FunctionProtoType::ExtProtoInfo FromEPI =
6738 FromFunctionType->getExtProtoInfo();
6739 FunctionProtoType::ExtProtoInfo ToEPI =
6740 ToFunctionType->getExtProtoInfo();
6741 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6742 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6743 ArgIdx != NumArgs; ++ArgIdx) {
6744 if (FromEPI.ConsumedArguments[ArgIdx] !=
6745 ToEPI.ConsumedArguments[ArgIdx])
6746 return false;
6747 }
6748 return true;
6749}
6750
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006751/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6752/// 'RHS' attributes and returns the merged version; including for function
6753/// return types.
6754QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6755 QualType LHSCan = getCanonicalType(LHS),
6756 RHSCan = getCanonicalType(RHS);
6757 // If two types are identical, they are compatible.
6758 if (LHSCan == RHSCan)
6759 return LHS;
6760 if (RHSCan->isFunctionType()) {
6761 if (!LHSCan->isFunctionType())
6762 return QualType();
6763 QualType OldReturnType =
6764 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6765 QualType NewReturnType =
6766 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6767 QualType ResReturnType =
6768 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6769 if (ResReturnType.isNull())
6770 return QualType();
6771 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6772 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6773 // In either case, use OldReturnType to build the new function type.
6774 const FunctionType *F = LHS->getAs<FunctionType>();
6775 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006776 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6777 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006778 QualType ResultType
6779 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006780 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006781 return ResultType;
6782 }
6783 }
6784 return QualType();
6785 }
6786
6787 // If the qualifiers are different, the types can still be merged.
6788 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6789 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6790 if (LQuals != RQuals) {
6791 // If any of these qualifiers are different, we have a type mismatch.
6792 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6793 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6794 return QualType();
6795
6796 // Exactly one GC qualifier difference is allowed: __strong is
6797 // okay if the other type has no GC qualifier but is an Objective
6798 // C object pointer (i.e. implicitly strong by default). We fix
6799 // this by pretending that the unqualified type was actually
6800 // qualified __strong.
6801 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6802 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6803 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6804
6805 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6806 return QualType();
6807
6808 if (GC_L == Qualifiers::Strong)
6809 return LHS;
6810 if (GC_R == Qualifiers::Strong)
6811 return RHS;
6812 return QualType();
6813 }
6814
6815 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6816 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6817 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6818 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6819 if (ResQT == LHSBaseQT)
6820 return LHS;
6821 if (ResQT == RHSBaseQT)
6822 return RHS;
6823 }
6824 return QualType();
6825}
6826
Chris Lattner5426bf62008-04-07 07:01:58 +00006827//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006828// Integer Predicates
6829//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006830
Jay Foad4ba2a172011-01-12 09:06:06 +00006831unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006832 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006833 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006834 if (T->isBooleanType())
6835 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006836 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006837 return (unsigned)getTypeSize(T);
6838}
6839
Abramo Bagnara762f1592012-09-09 10:21:24 +00006840QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00006841 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006842
6843 // Turn <4 x signed int> -> <4 x unsigned int>
6844 if (const VectorType *VTy = T->getAs<VectorType>())
6845 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006846 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006847
6848 // For enums, we return the unsigned version of the base type.
6849 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006850 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006851
6852 const BuiltinType *BTy = T->getAs<BuiltinType>();
6853 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006854 switch (BTy->getKind()) {
6855 case BuiltinType::Char_S:
6856 case BuiltinType::SChar:
6857 return UnsignedCharTy;
6858 case BuiltinType::Short:
6859 return UnsignedShortTy;
6860 case BuiltinType::Int:
6861 return UnsignedIntTy;
6862 case BuiltinType::Long:
6863 return UnsignedLongTy;
6864 case BuiltinType::LongLong:
6865 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006866 case BuiltinType::Int128:
6867 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006868 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006869 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006870 }
6871}
6872
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006873ASTMutationListener::~ASTMutationListener() { }
6874
Chris Lattner86df27b2009-06-14 00:45:47 +00006875
6876//===----------------------------------------------------------------------===//
6877// Builtin Type Computation
6878//===----------------------------------------------------------------------===//
6879
6880/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006881/// pointer over the consumed characters. This returns the resultant type. If
6882/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6883/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6884/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006885///
6886/// RequiresICE is filled in on return to indicate whether the value is required
6887/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006888static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006889 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006890 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006891 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006892 // Modifiers.
6893 int HowLong = 0;
6894 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006895 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006896
Chris Lattner33daae62010-10-01 22:42:38 +00006897 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006898 bool Done = false;
6899 while (!Done) {
6900 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006901 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006902 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006903 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006904 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006905 case 'S':
6906 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6907 assert(!Signed && "Can't use 'S' modifier multiple times!");
6908 Signed = true;
6909 break;
6910 case 'U':
6911 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6912 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6913 Unsigned = true;
6914 break;
6915 case 'L':
6916 assert(HowLong <= 2 && "Can't have LLLL modifier");
6917 ++HowLong;
6918 break;
6919 }
6920 }
6921
6922 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006923
Chris Lattner86df27b2009-06-14 00:45:47 +00006924 // Read the base type.
6925 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006926 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006927 case 'v':
6928 assert(HowLong == 0 && !Signed && !Unsigned &&
6929 "Bad modifiers used with 'v'!");
6930 Type = Context.VoidTy;
6931 break;
6932 case 'f':
6933 assert(HowLong == 0 && !Signed && !Unsigned &&
6934 "Bad modifiers used with 'f'!");
6935 Type = Context.FloatTy;
6936 break;
6937 case 'd':
6938 assert(HowLong < 2 && !Signed && !Unsigned &&
6939 "Bad modifiers used with 'd'!");
6940 if (HowLong)
6941 Type = Context.LongDoubleTy;
6942 else
6943 Type = Context.DoubleTy;
6944 break;
6945 case 's':
6946 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6947 if (Unsigned)
6948 Type = Context.UnsignedShortTy;
6949 else
6950 Type = Context.ShortTy;
6951 break;
6952 case 'i':
6953 if (HowLong == 3)
6954 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6955 else if (HowLong == 2)
6956 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6957 else if (HowLong == 1)
6958 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6959 else
6960 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6961 break;
6962 case 'c':
6963 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6964 if (Signed)
6965 Type = Context.SignedCharTy;
6966 else if (Unsigned)
6967 Type = Context.UnsignedCharTy;
6968 else
6969 Type = Context.CharTy;
6970 break;
6971 case 'b': // boolean
6972 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6973 Type = Context.BoolTy;
6974 break;
6975 case 'z': // size_t.
6976 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6977 Type = Context.getSizeType();
6978 break;
6979 case 'F':
6980 Type = Context.getCFConstantStringType();
6981 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006982 case 'G':
6983 Type = Context.getObjCIdType();
6984 break;
6985 case 'H':
6986 Type = Context.getObjCSelType();
6987 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006988 case 'a':
6989 Type = Context.getBuiltinVaListType();
6990 assert(!Type.isNull() && "builtin va list type not initialized!");
6991 break;
6992 case 'A':
6993 // This is a "reference" to a va_list; however, what exactly
6994 // this means depends on how va_list is defined. There are two
6995 // different kinds of va_list: ones passed by value, and ones
6996 // passed by reference. An example of a by-value va_list is
6997 // x86, where va_list is a char*. An example of by-ref va_list
6998 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6999 // we want this argument to be a char*&; for x86-64, we want
7000 // it to be a __va_list_tag*.
7001 Type = Context.getBuiltinVaListType();
7002 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007003 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007004 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007005 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007006 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007007 break;
7008 case 'V': {
7009 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007010 unsigned NumElements = strtoul(Str, &End, 10);
7011 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007012 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007013
Chris Lattner14e0e742010-10-01 22:53:11 +00007014 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7015 RequiresICE, false);
7016 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007017
7018 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007019 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007020 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007021 break;
7022 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007023 case 'E': {
7024 char *End;
7025
7026 unsigned NumElements = strtoul(Str, &End, 10);
7027 assert(End != Str && "Missing vector size");
7028
7029 Str = End;
7030
7031 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7032 false);
7033 Type = Context.getExtVectorType(ElementType, NumElements);
7034 break;
7035 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007036 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007037 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7038 false);
7039 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007040 Type = Context.getComplexType(ElementType);
7041 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007042 }
7043 case 'Y' : {
7044 Type = Context.getPointerDiffType();
7045 break;
7046 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007047 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007048 Type = Context.getFILEType();
7049 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007050 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007051 return QualType();
7052 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007053 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007054 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007055 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007056 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007057 else
7058 Type = Context.getjmp_bufType();
7059
Mike Stumpfd612db2009-07-28 23:47:15 +00007060 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007061 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007062 return QualType();
7063 }
7064 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007065 case 'K':
7066 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7067 Type = Context.getucontext_tType();
7068
7069 if (Type.isNull()) {
7070 Error = ASTContext::GE_Missing_ucontext;
7071 return QualType();
7072 }
7073 break;
Mike Stump782fa302009-07-28 02:25:19 +00007074 }
Mike Stump1eb44332009-09-09 15:08:12 +00007075
Chris Lattner33daae62010-10-01 22:42:38 +00007076 // If there are modifiers and if we're allowed to parse them, go for it.
7077 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007078 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007079 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007080 default: Done = true; --Str; break;
7081 case '*':
7082 case '&': {
7083 // Both pointers and references can have their pointee types
7084 // qualified with an address space.
7085 char *End;
7086 unsigned AddrSpace = strtoul(Str, &End, 10);
7087 if (End != Str && AddrSpace != 0) {
7088 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7089 Str = End;
7090 }
7091 if (c == '*')
7092 Type = Context.getPointerType(Type);
7093 else
7094 Type = Context.getLValueReferenceType(Type);
7095 break;
7096 }
7097 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7098 case 'C':
7099 Type = Type.withConst();
7100 break;
7101 case 'D':
7102 Type = Context.getVolatileType(Type);
7103 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007104 case 'R':
7105 Type = Type.withRestrict();
7106 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007107 }
7108 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007109
Chris Lattner14e0e742010-10-01 22:53:11 +00007110 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007111 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007112
Chris Lattner86df27b2009-06-14 00:45:47 +00007113 return Type;
7114}
7115
7116/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007117QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007118 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007119 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007120 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007121
Chris Lattner5f9e2722011-07-23 10:55:15 +00007122 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007123
Chris Lattner14e0e742010-10-01 22:53:11 +00007124 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007125 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007126 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7127 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007128 if (Error != GE_None)
7129 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007130
7131 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7132
Chris Lattner86df27b2009-06-14 00:45:47 +00007133 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007134 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007135 if (Error != GE_None)
7136 return QualType();
7137
Chris Lattner14e0e742010-10-01 22:53:11 +00007138 // If this argument is required to be an IntegerConstantExpression and the
7139 // caller cares, fill in the bitmask we return.
7140 if (RequiresICE && IntegerConstantArgs)
7141 *IntegerConstantArgs |= 1 << ArgTypes.size();
7142
Chris Lattner86df27b2009-06-14 00:45:47 +00007143 // Do array -> pointer decay. The builtin should use the decayed type.
7144 if (Ty->isArrayType())
7145 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007146
Chris Lattner86df27b2009-06-14 00:45:47 +00007147 ArgTypes.push_back(Ty);
7148 }
7149
7150 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7151 "'.' should only occur at end of builtin type list!");
7152
John McCall00ccbef2010-12-21 00:44:39 +00007153 FunctionType::ExtInfo EI;
7154 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7155
7156 bool Variadic = (TypeStr[0] == '.');
7157
7158 // We really shouldn't be making a no-proto type here, especially in C++.
7159 if (ArgTypes.empty() && Variadic)
7160 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007161
John McCalle23cf432010-12-14 08:05:40 +00007162 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007163 EPI.ExtInfo = EI;
7164 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007165
7166 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007167}
Eli Friedmana95d7572009-08-19 07:44:53 +00007168
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007169GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7170 GVALinkage External = GVA_StrongExternal;
7171
7172 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007173 switch (L) {
7174 case NoLinkage:
7175 case InternalLinkage:
7176 case UniqueExternalLinkage:
7177 return GVA_Internal;
7178
7179 case ExternalLinkage:
7180 switch (FD->getTemplateSpecializationKind()) {
7181 case TSK_Undeclared:
7182 case TSK_ExplicitSpecialization:
7183 External = GVA_StrongExternal;
7184 break;
7185
7186 case TSK_ExplicitInstantiationDefinition:
7187 return GVA_ExplicitTemplateInstantiation;
7188
7189 case TSK_ExplicitInstantiationDeclaration:
7190 case TSK_ImplicitInstantiation:
7191 External = GVA_TemplateInstantiation;
7192 break;
7193 }
7194 }
7195
7196 if (!FD->isInlined())
7197 return External;
7198
David Blaikie4e4d0842012-03-11 07:00:24 +00007199 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007200 // GNU or C99 inline semantics. Determine whether this symbol should be
7201 // externally visible.
7202 if (FD->isInlineDefinitionExternallyVisible())
7203 return External;
7204
7205 // C99 inline semantics, where the symbol is not externally visible.
7206 return GVA_C99Inline;
7207 }
7208
7209 // C++0x [temp.explicit]p9:
7210 // [ Note: The intent is that an inline function that is the subject of
7211 // an explicit instantiation declaration will still be implicitly
7212 // instantiated when used so that the body can be considered for
7213 // inlining, but that no out-of-line copy of the inline function would be
7214 // generated in the translation unit. -- end note ]
7215 if (FD->getTemplateSpecializationKind()
7216 == TSK_ExplicitInstantiationDeclaration)
7217 return GVA_C99Inline;
7218
7219 return GVA_CXXInline;
7220}
7221
7222GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7223 // If this is a static data member, compute the kind of template
7224 // specialization. Otherwise, this variable is not part of a
7225 // template.
7226 TemplateSpecializationKind TSK = TSK_Undeclared;
7227 if (VD->isStaticDataMember())
7228 TSK = VD->getTemplateSpecializationKind();
7229
7230 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00007231 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007232 VD->getType()->getLinkage() == UniqueExternalLinkage)
7233 L = UniqueExternalLinkage;
7234
7235 switch (L) {
7236 case NoLinkage:
7237 case InternalLinkage:
7238 case UniqueExternalLinkage:
7239 return GVA_Internal;
7240
7241 case ExternalLinkage:
7242 switch (TSK) {
7243 case TSK_Undeclared:
7244 case TSK_ExplicitSpecialization:
7245 return GVA_StrongExternal;
7246
7247 case TSK_ExplicitInstantiationDeclaration:
7248 llvm_unreachable("Variable should not be instantiated");
7249 // Fall through to treat this like any other instantiation.
7250
7251 case TSK_ExplicitInstantiationDefinition:
7252 return GVA_ExplicitTemplateInstantiation;
7253
7254 case TSK_ImplicitInstantiation:
7255 return GVA_TemplateInstantiation;
7256 }
7257 }
7258
David Blaikie7530c032012-01-17 06:56:22 +00007259 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007260}
7261
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007262bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007263 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7264 if (!VD->isFileVarDecl())
7265 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007266 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007267 return false;
7268
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007269 // Weak references don't produce any output by themselves.
7270 if (D->hasAttr<WeakRefAttr>())
7271 return false;
7272
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007273 // Aliases and used decls are required.
7274 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7275 return true;
7276
7277 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7278 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007279 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007280 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007281
7282 // Constructors and destructors are required.
7283 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7284 return true;
7285
7286 // The key function for a class is required.
7287 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7288 const CXXRecordDecl *RD = MD->getParent();
7289 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7290 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7291 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7292 return true;
7293 }
7294 }
7295
7296 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7297
7298 // static, static inline, always_inline, and extern inline functions can
7299 // always be deferred. Normal inline functions can be deferred in C99/C++.
7300 // Implicit template instantiations can also be deferred in C++.
7301 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007302 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007303 return false;
7304 return true;
7305 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007306
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007307 const VarDecl *VD = cast<VarDecl>(D);
7308 assert(VD->isFileVarDecl() && "Expected file scoped var");
7309
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007310 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7311 return false;
7312
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007313 // Structs that have non-trivial constructors or destructors are required.
7314
7315 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00007316 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007317 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7318 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00007319 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7320 RD->hasTrivialCopyConstructor() &&
7321 RD->hasTrivialMoveConstructor() &&
7322 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007323 return true;
7324 }
7325 }
7326
7327 GVALinkage L = GetGVALinkageForVariable(VD);
7328 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7329 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7330 return false;
7331 }
7332
7333 return true;
7334}
Charles Davis071cc7d2010-08-16 03:33:14 +00007335
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007336CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007337 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007338 return ABI->getDefaultMethodCallConv(isVariadic);
7339}
7340
7341CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7342 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7343 return CC_Default;
7344 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007345}
7346
Jay Foad4ba2a172011-01-12 09:06:06 +00007347bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007348 // Pass through to the C++ ABI object
7349 return ABI->isNearlyEmpty(RD);
7350}
7351
Peter Collingbourne14110472011-01-13 18:57:25 +00007352MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007353 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007354 case CXXABI_ARM:
7355 case CXXABI_Itanium:
7356 return createItaniumMangleContext(*this, getDiagnostics());
7357 case CXXABI_Microsoft:
7358 return createMicrosoftMangleContext(*this, getDiagnostics());
7359 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007360 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007361}
7362
Charles Davis071cc7d2010-08-16 03:33:14 +00007363CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007364
7365size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007366 return ASTRecordLayouts.getMemorySize()
7367 + llvm::capacity_in_bytes(ObjCLayouts)
7368 + llvm::capacity_in_bytes(KeyFunctions)
7369 + llvm::capacity_in_bytes(ObjCImpls)
7370 + llvm::capacity_in_bytes(BlockVarCopyInits)
7371 + llvm::capacity_in_bytes(DeclAttrs)
7372 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7373 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7374 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7375 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7376 + llvm::capacity_in_bytes(OverriddenMethods)
7377 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007378 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007379 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007380}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007381
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007382unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7383 CXXRecordDecl *Lambda = CallOperator->getParent();
7384 return LambdaMangleContexts[Lambda->getDeclContext()]
7385 .getManglingNumber(CallOperator);
7386}
7387
7388
Ted Kremenekd211cb72011-10-06 05:00:56 +00007389void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7390 ParamIndices[D] = index;
7391}
7392
7393unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7394 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7395 assert(I != ParamIndices.end() &&
7396 "ParmIndices lacks entry set by ParmVarDecl");
7397 return I->second;
7398}