blob: 0c2cc1c61718939845879fc3a317d48d9803025b [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000016#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000017#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000020#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000021#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000023#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000024#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000026#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000028#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000031#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000034#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000035#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000036#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000037
Chris Lattnerddc135e2006-11-10 06:34:16 +000038using namespace clang;
39
Douglas Gregor9672f922010-07-03 00:47:00 +000040unsigned ASTContext::NumImplicitDefaultConstructors;
41unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000042unsigned ASTContext::NumImplicitCopyConstructors;
43unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000044unsigned ASTContext::NumImplicitMoveConstructors;
45unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000046unsigned ASTContext::NumImplicitCopyAssignmentOperators;
47unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveAssignmentOperators;
49unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000050unsigned ASTContext::NumImplicitDestructors;
51unsigned ASTContext::NumImplicitDestructorsDeclared;
52
Steve Naroff0af91202007-04-27 21:51:21 +000053enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000054 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000055};
56
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000057RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000058 if (!CommentsLoaded && ExternalSource) {
59 ExternalSource->ReadComments();
60 CommentsLoaded = true;
61 }
62
63 assert(D);
64
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000065 // User can not attach documentation to implicit declarations.
66 if (D->isImplicit())
67 return NULL;
68
Dmitri Gribenkob2610882012-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 Gribenkob1ad9932012-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 Gribenkoaab83832012-06-20 00:34:58 +000091 // TODO: handle comments for function parameters properly.
92 if (isa<ParmVarDecl>(D))
93 return NULL;
94
Dmitri Gribenko34df2202012-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 Gribenko7dd29d42012-07-06 18:19:34 +0000102 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-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 Gribenkoe7bb9442012-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 Gribenko34df2202012-07-31 22:37:06 +0000116 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000117 isa<RedeclarableTemplateDecl>(D) ||
118 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000119 DeclLoc = D->getLocStart();
120 else
121 DeclLoc = D->getLocation();
122
Dmitri Gribenkoaab83832012-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 Gribenkoaab83832012-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 Gribenko82ea9472012-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 Gribenkoaab83832012-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 Gribenko7dd29d42012-07-06 18:19:34 +0000160 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000161 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000162 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000163 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-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 Gribenko7dd29d42012-07-06 18:19:34 +0000170 return *Comment;
Dmitri Gribenkoaab83832012-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 Gribenko7dd29d42012-07-06 18:19:34 +0000181 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000182 return NULL;
183
184 // Decompose the end of the comment.
185 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000186 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-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 Gribenko7e8729b2012-06-27 23:43:37 +0000204 // There should be no other declarations or preprocessor directives between
205 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000206 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000207 return NULL;
208
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000209 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000210}
211
Dmitri Gribenkob2610882012-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 Gribenko90631802012-08-22 17:44:32 +0000215/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000216const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000217 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000218 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000219 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-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 Gregor35ceb272012-08-13 16:37:30 +0000236 }
Dmitri Gribenko90631802012-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 Gribenkob2610882012-08-14 17:17:18 +0000281 return D;
282}
283} // unnamed namespace
284
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000285const RawComment *ASTContext::getRawCommentForAnyRedecl(
286 const Decl *D,
287 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000288 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000289
Dmitri Gribenkoa43ec182012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000296 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
297 if (OriginalDecl)
298 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000299 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000300 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000301 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000302 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000303
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000304 // Search for comments attached to declarations in the redeclaration chain.
305 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000306 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000316 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000317 break;
318 }
319 } else {
320 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000321 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000328 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000329 RedeclComments[*I] = Raw;
330 if (RC)
331 break;
332 }
333 }
334
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000335 // If we found a comment, it should be a documentation comment.
336 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000338 if (OriginalDecl)
339 *OriginalDecl = OriginalDeclForRC;
340
Dmitri Gribenkoa43ec182012-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 Gribenko4ae66a32012-08-16 18:19:43 +0000345 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-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 Gribenkoaab83832012-06-20 00:34:58 +0000355 return RC;
356}
357
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000358comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000359 D = adjustDeclToTemplate(D);
360 const Decl *Canonical = D->getCanonicalDecl();
361 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
362 ParsedComments.find(Canonical);
363 if (Pos != ParsedComments.end())
364 return Pos->second;
365
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000366 const Decl *OriginalDecl;
367 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000368 if (!RC)
369 return NULL;
370
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000371 // If the RawComment was attached to other redeclaration of this Decl, we
372 // should parse the comment in context of that other Decl. This is important
373 // because comments can contain references to parameter names which can be
374 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000375 if (D != OriginalDecl)
376 return getCommentForDecl(OriginalDecl);
377
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000378 comments::FullComment *FC = RC->parse(*this, D);
379 ParsedComments[Canonical] = FC;
380 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000381}
382
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000383void
384ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
385 TemplateTemplateParmDecl *Parm) {
386 ID.AddInteger(Parm->getDepth());
387 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000388 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000389
390 TemplateParameterList *Params = Parm->getTemplateParameters();
391 ID.AddInteger(Params->size());
392 for (TemplateParameterList::const_iterator P = Params->begin(),
393 PEnd = Params->end();
394 P != PEnd; ++P) {
395 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
396 ID.AddInteger(0);
397 ID.AddBoolean(TTP->isParameterPack());
398 continue;
399 }
400
401 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
402 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000403 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000404 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000405 if (NTTP->isExpandedParameterPack()) {
406 ID.AddBoolean(true);
407 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000408 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
409 QualType T = NTTP->getExpansionType(I);
410 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
411 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000412 } else
413 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000414 continue;
415 }
416
417 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
418 ID.AddInteger(2);
419 Profile(ID, TTP);
420 }
421}
422
423TemplateTemplateParmDecl *
424ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000425 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000426 // Check if we already have a canonical template template parameter.
427 llvm::FoldingSetNodeID ID;
428 CanonicalTemplateTemplateParm::Profile(ID, TTP);
429 void *InsertPos = 0;
430 CanonicalTemplateTemplateParm *Canonical
431 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
432 if (Canonical)
433 return Canonical->getParam();
434
435 // Build a canonical template parameter list.
436 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000438 CanonParams.reserve(Params->size());
439 for (TemplateParameterList::const_iterator P = Params->begin(),
440 PEnd = Params->end();
441 P != PEnd; ++P) {
442 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
443 CanonParams.push_back(
444 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000445 SourceLocation(),
446 SourceLocation(),
447 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000448 TTP->getIndex(), 0, false,
449 TTP->isParameterPack()));
450 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000451 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
452 QualType T = getCanonicalType(NTTP->getType());
453 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
454 NonTypeTemplateParmDecl *Param;
455 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456 SmallVector<QualType, 2> ExpandedTypes;
457 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000458 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
459 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
460 ExpandedTInfos.push_back(
461 getTrivialTypeSourceInfo(ExpandedTypes.back()));
462 }
463
464 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000465 SourceLocation(),
466 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000467 NTTP->getDepth(),
468 NTTP->getPosition(), 0,
469 T,
470 TInfo,
471 ExpandedTypes.data(),
472 ExpandedTypes.size(),
473 ExpandedTInfos.data());
474 } else {
475 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000476 SourceLocation(),
477 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000478 NTTP->getDepth(),
479 NTTP->getPosition(), 0,
480 T,
481 NTTP->isParameterPack(),
482 TInfo);
483 }
484 CanonParams.push_back(Param);
485
486 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000487 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
488 cast<TemplateTemplateParmDecl>(*P)));
489 }
490
491 TemplateTemplateParmDecl *CanonTTP
492 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
493 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000494 TTP->getPosition(),
495 TTP->isParameterPack(),
496 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000497 TemplateParameterList::Create(*this, SourceLocation(),
498 SourceLocation(),
499 CanonParams.data(),
500 CanonParams.size(),
501 SourceLocation()));
502
503 // Get the new insert position for the node we care about.
504 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
505 assert(Canonical == 0 && "Shouldn't be in the map!");
506 (void)Canonical;
507
508 // Create the canonical template template parameter entry.
509 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
510 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
511 return CanonTTP;
512}
513
Charles Davis53c59df2010-08-16 03:33:14 +0000514CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000515 if (!LangOpts.CPlusPlus) return 0;
516
Charles Davis6bcb07a2010-08-19 02:18:14 +0000517 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000518 case CXXABI_ARM:
519 return CreateARMCXXABI(*this);
520 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000521 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000522 case CXXABI_Microsoft:
523 return CreateMicrosoftCXXABI(*this);
524 }
David Blaikie8a40f702012-01-17 06:56:22 +0000525 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000526}
527
Douglas Gregore8bbc122011-09-02 00:18:52 +0000528static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000529 const LangOptions &LOpts) {
530 if (LOpts.FakeAddressSpaceMap) {
531 // The fake address space map must have a distinct entry for each
532 // language-specific address space.
533 static const unsigned FakeAddrSpaceMap[] = {
534 1, // opencl_global
535 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000536 3, // opencl_constant
537 4, // cuda_device
538 5, // cuda_constant
539 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000540 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000541 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000542 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000543 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000544 }
545}
546
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000547ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000548 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000549 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000550 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000551 unsigned size_reserve,
552 bool DelayInitialization)
553 : FunctionProtoTypes(this_()),
554 TemplateSpecializationTypes(this_()),
555 DependentTemplateSpecializationTypes(this_()),
556 SubstTemplateTemplateParmPacks(this_()),
557 GlobalNestedNameSpecifier(0),
558 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000559 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000560 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000561 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000562 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000563 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
564 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
565 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000566 NullTypeSourceInfo(QualType()),
567 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000568 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000569 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000570 Idents(idents), Selectors(sels),
571 BuiltinInfo(builtins),
572 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000573 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000574 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000575 LastSDM(0, 0),
576 UniqueBlockByRefTypeID(0)
577{
Mike Stump11289f42009-09-09 15:08:12 +0000578 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000579 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000580
581 if (!DelayInitialization) {
582 assert(t && "No target supplied for ASTContext initialization");
583 InitBuiltinTypes(*t);
584 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000585}
586
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000587ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000588 // Release the DenseMaps associated with DeclContext objects.
589 // FIXME: Is this the ideal solution?
590 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000591
Douglas Gregor5b11d492010-07-25 17:53:33 +0000592 // Call all of the deallocation functions.
593 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
594 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000595
Ted Kremenek076baeb2010-06-08 23:00:58 +0000596 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000597 // because they can contain DenseMaps.
598 for (llvm::DenseMap<const ObjCContainerDecl*,
599 const ASTRecordLayout*>::iterator
600 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
601 // Increment in loop to prevent using deallocated memory.
602 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
603 R->Destroy(*this);
604
Ted Kremenek076baeb2010-06-08 23:00:58 +0000605 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
606 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
607 // Increment in loop to prevent using deallocated memory.
608 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
609 R->Destroy(*this);
610 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000611
612 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
613 AEnd = DeclAttrs.end();
614 A != AEnd; ++A)
615 A->second->~AttrVec();
616}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000617
Douglas Gregor1a809332010-05-23 18:26:36 +0000618void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
619 Deallocations.push_back(std::make_pair(Callback, Data));
620}
621
Mike Stump11289f42009-09-09 15:08:12 +0000622void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000623ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000624 ExternalSource.reset(Source.take());
625}
626
Chris Lattner4eb445d2007-01-26 01:27:23 +0000627void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000628 llvm::errs() << "\n*** AST Context Stats:\n";
629 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000630
Douglas Gregora30d0462009-05-26 14:40:08 +0000631 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000632#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000633#define ABSTRACT_TYPE(Name, Parent)
634#include "clang/AST/TypeNodes.def"
635 0 // Extra
636 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000637
Chris Lattner4eb445d2007-01-26 01:27:23 +0000638 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
639 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000640 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000641 }
642
Douglas Gregora30d0462009-05-26 14:40:08 +0000643 unsigned Idx = 0;
644 unsigned TotalBytes = 0;
645#define TYPE(Name, Parent) \
646 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000647 llvm::errs() << " " << counts[Idx] << " " << #Name \
648 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000649 TotalBytes += counts[Idx] * sizeof(Name##Type); \
650 ++Idx;
651#define ABSTRACT_TYPE(Name, Parent)
652#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000653
Chandler Carruth3c147a72011-07-04 05:32:14 +0000654 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
655
Douglas Gregor7454c562010-07-02 20:37:36 +0000656 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000657 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
658 << NumImplicitDefaultConstructors
659 << " implicit default constructors created\n";
660 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
661 << NumImplicitCopyConstructors
662 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000663 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000664 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
665 << NumImplicitMoveConstructors
666 << " implicit move constructors created\n";
667 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
668 << NumImplicitCopyAssignmentOperators
669 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000670 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000671 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
672 << NumImplicitMoveAssignmentOperators
673 << " implicit move assignment operators created\n";
674 llvm::errs() << NumImplicitDestructorsDeclared << "/"
675 << NumImplicitDestructors
676 << " implicit destructors created\n";
677
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000678 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000679 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000680 ExternalSource->PrintStats();
681 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000682
Douglas Gregor5b11d492010-07-25 17:53:33 +0000683 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000684}
685
Douglas Gregor801c99d2011-08-12 06:49:56 +0000686TypedefDecl *ASTContext::getInt128Decl() const {
687 if (!Int128Decl) {
688 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
689 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
690 getTranslationUnitDecl(),
691 SourceLocation(),
692 SourceLocation(),
693 &Idents.get("__int128_t"),
694 TInfo);
695 }
696
697 return Int128Decl;
698}
699
700TypedefDecl *ASTContext::getUInt128Decl() const {
701 if (!UInt128Decl) {
702 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
703 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
704 getTranslationUnitDecl(),
705 SourceLocation(),
706 SourceLocation(),
707 &Idents.get("__uint128_t"),
708 TInfo);
709 }
710
711 return UInt128Decl;
712}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000713
John McCall48f2d582009-10-23 23:03:21 +0000714void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000715 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000716 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000717 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000718}
719
Douglas Gregore8bbc122011-09-02 00:18:52 +0000720void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
721 assert((!this->Target || this->Target == &Target) &&
722 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000723 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000724
Douglas Gregore8bbc122011-09-02 00:18:52 +0000725 this->Target = &Target;
726
727 ABI.reset(createCXXABI(Target));
728 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
729
Chris Lattner970e54e2006-11-12 00:37:36 +0000730 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000731 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattner970e54e2006-11-12 00:37:36 +0000733 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000734 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000735 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000736 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000737 InitBuiltinType(CharTy, BuiltinType::Char_S);
738 else
739 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000740 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000741 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
742 InitBuiltinType(ShortTy, BuiltinType::Short);
743 InitBuiltinType(IntTy, BuiltinType::Int);
744 InitBuiltinType(LongTy, BuiltinType::Long);
745 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000746
Chris Lattner970e54e2006-11-12 00:37:36 +0000747 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000748 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
749 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
750 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
751 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
752 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000753
Chris Lattner970e54e2006-11-12 00:37:36 +0000754 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000755 InitBuiltinType(FloatTy, BuiltinType::Float);
756 InitBuiltinType(DoubleTy, BuiltinType::Double);
757 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000758
Chris Lattnerf122cef2009-04-30 02:43:43 +0000759 // GNU extension, 128-bit integers.
760 InitBuiltinType(Int128Ty, BuiltinType::Int128);
761 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
762
Chris Lattnerad3467e2010-12-25 23:25:43 +0000763 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000764 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000765 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
766 else // -fshort-wchar makes wchar_t be unsigned.
767 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
768 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000769 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000770
James Molloy36365542012-05-04 10:55:22 +0000771 WIntTy = getFromTargetType(Target.getWIntType());
772
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000773 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
774 InitBuiltinType(Char16Ty, BuiltinType::Char16);
775 else // C99
776 Char16Ty = getFromTargetType(Target.getChar16Type());
777
778 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
779 InitBuiltinType(Char32Ty, BuiltinType::Char32);
780 else // C99
781 Char32Ty = getFromTargetType(Target.getChar32Type());
782
Douglas Gregor4619e432008-12-05 23:32:09 +0000783 // Placeholder type for type-dependent expressions whose type is
784 // completely unknown. No code should ever check a type against
785 // DependentTy and users should never see it; however, it is here to
786 // help diagnose failures to properly check for type-dependent
787 // expressions.
788 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789
John McCall36e7fe32010-10-12 00:20:44 +0000790 // Placeholder type for functions.
791 InitBuiltinType(OverloadTy, BuiltinType::Overload);
792
John McCall0009fcc2011-04-26 20:42:42 +0000793 // Placeholder type for bound members.
794 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
795
John McCall526ab472011-10-25 17:37:35 +0000796 // Placeholder type for pseudo-objects.
797 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
798
John McCall31996342011-04-07 08:22:57 +0000799 // "any" type; useful for debugger-like clients.
800 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
801
John McCall8a6b59a2011-10-17 18:09:15 +0000802 // Placeholder type for unbridged ARC casts.
803 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
804
Chris Lattner970e54e2006-11-12 00:37:36 +0000805 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000806 FloatComplexTy = getComplexType(FloatTy);
807 DoubleComplexTy = getComplexType(DoubleTy);
808 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000809
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000810 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000811 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
812 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000813 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000814
815 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000816 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
817 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000818
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000819 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000820
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000821 // void * type
822 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000823
824 // nullptr type (C++0x 2.14.7)
825 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000826
827 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
828 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000829
830 // Builtin type used to help define __builtin_va_list.
831 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000832}
833
David Blaikie9c902b52011-09-25 23:23:43 +0000834DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000835 return SourceMgr.getDiagnostics();
836}
837
Douglas Gregor561eceb2010-08-30 16:49:28 +0000838AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
839 AttrVec *&Result = DeclAttrs[D];
840 if (!Result) {
841 void *Mem = Allocate(sizeof(AttrVec));
842 Result = new (Mem) AttrVec;
843 }
844
845 return *Result;
846}
847
848/// \brief Erase the attributes corresponding to the given declaration.
849void ASTContext::eraseDeclAttrs(const Decl *D) {
850 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
851 if (Pos != DeclAttrs.end()) {
852 Pos->second->~AttrVec();
853 DeclAttrs.erase(Pos);
854 }
855}
856
Douglas Gregor86d142a2009-10-08 07:24:58 +0000857MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000858ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000859 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000860 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000861 = InstantiatedFromStaticDataMember.find(Var);
862 if (Pos == InstantiatedFromStaticDataMember.end())
863 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000864
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000865 return Pos->second;
866}
867
Mike Stump11289f42009-09-09 15:08:12 +0000868void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000869ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000870 TemplateSpecializationKind TSK,
871 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000872 assert(Inst->isStaticDataMember() && "Not a static data member");
873 assert(Tmpl->isStaticDataMember() && "Not a static data member");
874 assert(!InstantiatedFromStaticDataMember[Inst] &&
875 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000876 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000877 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000878}
879
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000880FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
881 const FunctionDecl *FD){
882 assert(FD && "Specialization is 0");
883 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000884 = ClassScopeSpecializationPattern.find(FD);
885 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000886 return 0;
887
888 return Pos->second;
889}
890
891void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
892 FunctionDecl *Pattern) {
893 assert(FD && "Specialization is 0");
894 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000895 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000896}
897
John McCalle61f2ba2009-11-18 02:36:19 +0000898NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000899ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000900 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000901 = InstantiatedFromUsingDecl.find(UUD);
902 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000903 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000904
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000905 return Pos->second;
906}
907
908void
John McCallb96ec562009-12-04 22:46:56 +0000909ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
910 assert((isa<UsingDecl>(Pattern) ||
911 isa<UnresolvedUsingValueDecl>(Pattern) ||
912 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
913 "pattern decl is not a using decl");
914 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
915 InstantiatedFromUsingDecl[Inst] = Pattern;
916}
917
918UsingShadowDecl *
919ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
920 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
921 = InstantiatedFromUsingShadowDecl.find(Inst);
922 if (Pos == InstantiatedFromUsingShadowDecl.end())
923 return 0;
924
925 return Pos->second;
926}
927
928void
929ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
930 UsingShadowDecl *Pattern) {
931 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
932 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000933}
934
Anders Carlsson5da84842009-09-01 04:26:58 +0000935FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
936 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
937 = InstantiatedFromUnnamedFieldDecl.find(Field);
938 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
939 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000940
Anders Carlsson5da84842009-09-01 04:26:58 +0000941 return Pos->second;
942}
943
944void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
945 FieldDecl *Tmpl) {
946 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
947 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
948 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
949 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000950
Anders Carlsson5da84842009-09-01 04:26:58 +0000951 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
952}
953
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000954bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
955 const FieldDecl *LastFD) const {
956 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000957 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000958}
959
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000960bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
961 const FieldDecl *LastFD) const {
962 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000963 FD->getBitWidthValue(*this) == 0 &&
964 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000965}
966
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000967bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
968 const FieldDecl *LastFD) const {
969 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000970 FD->getBitWidthValue(*this) &&
971 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000972}
973
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000974bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000975 const FieldDecl *LastFD) const {
976 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000977 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000978}
979
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000980bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000981 const FieldDecl *LastFD) const {
982 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000983 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000984}
985
Douglas Gregor832940b2010-03-02 23:58:15 +0000986ASTContext::overridden_cxx_method_iterator
987ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
988 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
989 = OverriddenMethods.find(Method);
990 if (Pos == OverriddenMethods.end())
991 return 0;
992
993 return Pos->second.begin();
994}
995
996ASTContext::overridden_cxx_method_iterator
997ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
998 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
999 = OverriddenMethods.find(Method);
1000 if (Pos == OverriddenMethods.end())
1001 return 0;
1002
1003 return Pos->second.end();
1004}
1005
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001006unsigned
1007ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1008 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1009 = OverriddenMethods.find(Method);
1010 if (Pos == OverriddenMethods.end())
1011 return 0;
1012
1013 return Pos->second.size();
1014}
1015
Douglas Gregor832940b2010-03-02 23:58:15 +00001016void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1017 const CXXMethodDecl *Overridden) {
1018 OverriddenMethods[Method].push_back(Overridden);
1019}
1020
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001021void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1022 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1023 assert(!Import->isFromASTFile() && "Non-local import declaration");
1024 if (!FirstLocalImport) {
1025 FirstLocalImport = Import;
1026 LastLocalImport = Import;
1027 return;
1028 }
1029
1030 LastLocalImport->NextLocalImport = Import;
1031 LastLocalImport = Import;
1032}
1033
Chris Lattner53cfe802007-07-18 17:52:12 +00001034//===----------------------------------------------------------------------===//
1035// Type Sizing and Analysis
1036//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001037
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001038/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1039/// scalar floating point type.
1040const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001041 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001042 assert(BT && "Not a floating point type!");
1043 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001044 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001045 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001046 case BuiltinType::Float: return Target->getFloatFormat();
1047 case BuiltinType::Double: return Target->getDoubleFormat();
1048 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001049 }
1050}
1051
Ken Dyck160146e2010-01-27 17:10:57 +00001052/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001053/// specified decl. Note that bitfields do not have a valid alignment, so
1054/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001055/// If @p RefAsPointee, references are treated like their underlying type
1056/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001057CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001058 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001059
John McCall94268702010-10-08 18:24:19 +00001060 bool UseAlignAttrOnly = false;
1061 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1062 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001063
John McCall94268702010-10-08 18:24:19 +00001064 // __attribute__((aligned)) can increase or decrease alignment
1065 // *except* on a struct or struct member, where it only increases
1066 // alignment unless 'packed' is also specified.
1067 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001068 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001069 // ignore that possibility; Sema should diagnose it.
1070 if (isa<FieldDecl>(D)) {
1071 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1072 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1073 } else {
1074 UseAlignAttrOnly = true;
1075 }
1076 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001077 else if (isa<FieldDecl>(D))
1078 UseAlignAttrOnly =
1079 D->hasAttr<PackedAttr>() ||
1080 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001081
John McCall4e819612011-01-20 07:57:12 +00001082 // If we're using the align attribute only, just ignore everything
1083 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001084 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001085 // do nothing
1086
John McCall94268702010-10-08 18:24:19 +00001087 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001088 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001089 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001090 if (RefAsPointee)
1091 T = RT->getPointeeType();
1092 else
1093 T = getPointerType(RT->getPointeeType());
1094 }
1095 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001096 // Adjust alignments of declarations with array type by the
1097 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001099 const ArrayType *arrayType;
1100 if (MinWidth && (arrayType = getAsArrayType(T))) {
1101 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001102 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001103 else if (isa<ConstantArrayType>(arrayType) &&
1104 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001105 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001106
John McCall33ddac02011-01-19 10:06:00 +00001107 // Walk through any array types while we're at it.
1108 T = getBaseElementType(arrayType);
1109 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001110 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001111 }
John McCall4e819612011-01-20 07:57:12 +00001112
1113 // Fields can be subject to extra alignment constraints, like if
1114 // the field is packed, the struct is packed, or the struct has a
1115 // a max-field-alignment constraint (#pragma pack). So calculate
1116 // the actual alignment of the field within the struct, and then
1117 // (as we're expected to) constrain that by the alignment of the type.
1118 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1119 // So calculate the alignment of the field.
1120 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1121
1122 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001123 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001124
1125 // Use the GCD of that and the offset within the record.
1126 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1127 if (offset > 0) {
1128 // Alignment is always a power of 2, so the GCD will be a power of 2,
1129 // which means we get to do this crazy thing instead of Euclid's.
1130 uint64_t lowBitOfOffset = offset & (~offset + 1);
1131 if (lowBitOfOffset < fieldAlign)
1132 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1133 }
1134
1135 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001136 }
Chris Lattner68061312009-01-24 21:53:27 +00001137 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001138
Ken Dyckcc56c542011-01-15 18:38:59 +00001139 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001140}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001141
John McCallf1249922012-08-21 04:10:00 +00001142// getTypeInfoDataSizeInChars - Return the size of a type, in
1143// chars. If the type is a record, its data size is returned. This is
1144// the size of the memcpy that's performed when assigning this type
1145// using a trivial copy/move assignment operator.
1146std::pair<CharUnits, CharUnits>
1147ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1148 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1149
1150 // In C++, objects can sometimes be allocated into the tail padding
1151 // of a base-class subobject. We decide whether that's possible
1152 // during class layout, so here we can just trust the layout results.
1153 if (getLangOpts().CPlusPlus) {
1154 if (const RecordType *RT = T->getAs<RecordType>()) {
1155 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1156 sizeAndAlign.first = layout.getDataSize();
1157 }
1158 }
1159
1160 return sizeAndAlign;
1161}
1162
John McCall87fe5d52010-05-20 01:18:31 +00001163std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001164ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001165 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001166 return std::make_pair(toCharUnitsFromBits(Info.first),
1167 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001168}
1169
1170std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001171ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001172 return getTypeInfoInChars(T.getTypePtr());
1173}
1174
Daniel Dunbarc6475872012-03-09 04:12:54 +00001175std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1176 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1177 if (it != MemoizedTypeInfo.end())
1178 return it->second;
1179
1180 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1181 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1182 return Info;
1183}
1184
1185/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1186/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001187///
1188/// FIXME: Pointers into different addr spaces could have different sizes and
1189/// alignment requirements: getPointerInfo should take an AddrSpace, this
1190/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001191std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001192ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001193 uint64_t Width=0;
1194 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001195 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001196#define TYPE(Class, Base)
1197#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001198#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001199#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1200#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001201 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001202
Chris Lattner355332d2007-07-13 22:27:08 +00001203 case Type::FunctionNoProto:
1204 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001205 // GCC extension: alignof(function) = 32 bits
1206 Width = 0;
1207 Align = 32;
1208 break;
1209
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001210 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001211 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001212 Width = 0;
1213 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1214 break;
1215
Steve Naroff5c131802007-08-30 01:06:46 +00001216 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001217 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001218
Chris Lattner37e05872008-03-05 18:54:05 +00001219 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001220 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001221 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1222 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001223 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001224 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001225 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001226 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001227 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001228 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001229 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001230 const VectorType *VT = cast<VectorType>(T);
1231 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1232 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001233 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001234 // If the alignment is not a power of 2, round up to the next power of 2.
1235 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001236 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001237 Align = llvm::NextPowerOf2(Align);
1238 Width = llvm::RoundUpToAlignment(Width, Align);
1239 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001240 // Adjust the alignment based on the target max.
1241 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1242 if (TargetVectorAlign && TargetVectorAlign < Align)
1243 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001244 break;
1245 }
Chris Lattner647fb222007-07-18 18:26:58 +00001246
Chris Lattner7570e9c2008-03-08 08:52:55 +00001247 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001248 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001249 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001250 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001251 // GCC extension: alignof(void) = 8 bits.
1252 Width = 0;
1253 Align = 8;
1254 break;
1255
Chris Lattner6a4f7452007-12-19 19:23:28 +00001256 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001257 Width = Target->getBoolWidth();
1258 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001259 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001260 case BuiltinType::Char_S:
1261 case BuiltinType::Char_U:
1262 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001263 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001264 Width = Target->getCharWidth();
1265 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001266 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001267 case BuiltinType::WChar_S:
1268 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001269 Width = Target->getWCharWidth();
1270 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001271 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001272 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001273 Width = Target->getChar16Width();
1274 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001275 break;
1276 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001277 Width = Target->getChar32Width();
1278 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001279 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001280 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001281 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001282 Width = Target->getShortWidth();
1283 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001284 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001285 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001286 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001287 Width = Target->getIntWidth();
1288 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001289 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001290 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001291 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001292 Width = Target->getLongWidth();
1293 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001294 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001295 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001296 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001297 Width = Target->getLongLongWidth();
1298 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001299 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001300 case BuiltinType::Int128:
1301 case BuiltinType::UInt128:
1302 Width = 128;
1303 Align = 128; // int128_t is 128-bit aligned on all targets.
1304 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001305 case BuiltinType::Half:
1306 Width = Target->getHalfWidth();
1307 Align = Target->getHalfAlign();
1308 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001309 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001310 Width = Target->getFloatWidth();
1311 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001312 break;
1313 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001314 Width = Target->getDoubleWidth();
1315 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001316 break;
1317 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001318 Width = Target->getLongDoubleWidth();
1319 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001320 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001321 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001322 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1323 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001324 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001325 case BuiltinType::ObjCId:
1326 case BuiltinType::ObjCClass:
1327 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001328 Width = Target->getPointerWidth(0);
1329 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001330 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001331 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001332 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001333 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001334 Width = Target->getPointerWidth(0);
1335 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001336 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001337 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001338 unsigned AS = getTargetAddressSpace(
1339 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001340 Width = Target->getPointerWidth(AS);
1341 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001342 break;
1343 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001344 case Type::LValueReference:
1345 case Type::RValueReference: {
1346 // alignof and sizeof should never enter this code path here, so we go
1347 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001348 unsigned AS = getTargetAddressSpace(
1349 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001350 Width = Target->getPointerWidth(AS);
1351 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001352 break;
1353 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001354 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001355 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001356 Width = Target->getPointerWidth(AS);
1357 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001358 break;
1359 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001360 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001361 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001362 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001363 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001364 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001365 Align = PtrDiffInfo.second;
1366 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001367 }
Chris Lattner647fb222007-07-18 18:26:58 +00001368 case Type::Complex: {
1369 // Complex types have the same alignment as their elements, but twice the
1370 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001371 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001372 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001373 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001374 Align = EltInfo.second;
1375 break;
1376 }
John McCall8b07ec22010-05-15 11:32:37 +00001377 case Type::ObjCObject:
1378 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001379 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001380 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001381 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001382 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001383 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001384 break;
1385 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001386 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001387 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001388 const TagType *TT = cast<TagType>(T);
1389
1390 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001391 Width = 8;
1392 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001393 break;
1394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001396 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001397 return getTypeInfo(ET->getDecl()->getIntegerType());
1398
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001399 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001400 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001401 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001402 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001403 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001404 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001405
Chris Lattner63d2b362009-10-22 05:17:15 +00001406 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001407 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1408 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001409
Richard Smith30482bc2011-02-20 03:19:35 +00001410 case Type::Auto: {
1411 const AutoType *A = cast<AutoType>(T);
1412 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001413 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001414 }
1415
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001416 case Type::Paren:
1417 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1418
Douglas Gregoref462e62009-04-30 17:32:17 +00001419 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001420 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001421 std::pair<uint64_t, unsigned> Info
1422 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001423 // If the typedef has an aligned attribute on it, it overrides any computed
1424 // alignment we have. This violates the GCC documentation (which says that
1425 // attribute(aligned) can only round up) but matches its implementation.
1426 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1427 Align = AttrAlign;
1428 else
1429 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001430 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001431 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001432 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001433
1434 case Type::TypeOfExpr:
1435 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1436 .getTypePtr());
1437
1438 case Type::TypeOf:
1439 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1440
Anders Carlsson81df7b82009-06-24 19:06:50 +00001441 case Type::Decltype:
1442 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1443 .getTypePtr());
1444
Alexis Hunte852b102011-05-24 22:41:36 +00001445 case Type::UnaryTransform:
1446 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1447
Abramo Bagnara6150c882010-05-11 21:36:43 +00001448 case Type::Elaborated:
1449 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001450
John McCall81904512011-01-06 01:58:22 +00001451 case Type::Attributed:
1452 return getTypeInfo(
1453 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1454
Richard Smith3f1b5d02011-05-05 21:57:07 +00001455 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001456 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001457 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001458 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1459 // A type alias template specialization may refer to a typedef with the
1460 // aligned attribute on it.
1461 if (TST->isTypeAlias())
1462 return getTypeInfo(TST->getAliasedType().getTypePtr());
1463 else
1464 return getTypeInfo(getCanonicalType(T));
1465 }
1466
Eli Friedman0dfb8892011-10-06 23:00:33 +00001467 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001468 std::pair<uint64_t, unsigned> Info
1469 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1470 Width = Info.first;
1471 Align = Info.second;
1472 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1473 llvm::isPowerOf2_64(Width)) {
1474 // We can potentially perform lock-free atomic operations for this
1475 // type; promote the alignment appropriately.
1476 // FIXME: We could potentially promote the width here as well...
1477 // is that worthwhile? (Non-struct atomic types generally have
1478 // power-of-two size anyway, but structs might not. Requires a bit
1479 // of implementation work to make sure we zero out the extra bits.)
1480 Align = static_cast<unsigned>(Width);
1481 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001482 }
1483
Douglas Gregoref462e62009-04-30 17:32:17 +00001484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001486 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001487 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001488}
1489
Ken Dyckcc56c542011-01-15 18:38:59 +00001490/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1491CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1492 return CharUnits::fromQuantity(BitSize / getCharWidth());
1493}
1494
Ken Dyckb0fcc592011-02-11 01:54:29 +00001495/// toBits - Convert a size in characters to a size in characters.
1496int64_t ASTContext::toBits(CharUnits CharSize) const {
1497 return CharSize.getQuantity() * getCharWidth();
1498}
1499
Ken Dyck8c89d592009-12-22 14:23:30 +00001500/// getTypeSizeInChars - Return the size of the specified type, in characters.
1501/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001502CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001503 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001504}
Jay Foad39c79802011-01-12 09:06:06 +00001505CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001506 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001507}
1508
Ken Dycka6046ab2010-01-26 17:25:18 +00001509/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001510/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001511CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001512 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001513}
Jay Foad39c79802011-01-12 09:06:06 +00001514CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001515 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001516}
1517
Chris Lattnera3402cd2009-01-27 18:08:34 +00001518/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1519/// type for the current target in bits. This can be different than the ABI
1520/// alignment in cases where it is beneficial for performance to overalign
1521/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001522unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001523 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001524
1525 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001526 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001527 T = CT->getElementType().getTypePtr();
1528 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001529 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1530 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001531 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1532
Chris Lattnera3402cd2009-01-27 18:08:34 +00001533 return ABIAlign;
1534}
1535
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001536/// DeepCollectObjCIvars -
1537/// This routine first collects all declared, but not synthesized, ivars in
1538/// super class and then collects all ivars, including those synthesized for
1539/// current class. This routine is used for implementation of current class
1540/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001541///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001542void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1543 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001544 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001545 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1546 DeepCollectObjCIvars(SuperClass, false, Ivars);
1547 if (!leafClass) {
1548 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1549 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001550 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001551 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001552 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001553 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001554 Iv= Iv->getNextIvar())
1555 Ivars.push_back(Iv);
1556 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001557}
1558
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001559/// CollectInheritedProtocols - Collect all protocols in current class and
1560/// those inherited by it.
1561void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001562 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001563 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001564 // We can use protocol_iterator here instead of
1565 // all_referenced_protocol_iterator since we are walking all categories.
1566 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1567 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001568 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001569 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001570 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001571 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001572 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001573 CollectInheritedProtocols(*P, Protocols);
1574 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001575 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001576
1577 // Categories of this Interface.
1578 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1579 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1580 CollectInheritedProtocols(CDeclChain, Protocols);
1581 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1582 while (SD) {
1583 CollectInheritedProtocols(SD, Protocols);
1584 SD = SD->getSuperClass();
1585 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001586 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001587 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001588 PE = OC->protocol_end(); P != PE; ++P) {
1589 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001590 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001591 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1592 PE = Proto->protocol_end(); P != PE; ++P)
1593 CollectInheritedProtocols(*P, Protocols);
1594 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001595 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001596 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1597 PE = OP->protocol_end(); P != PE; ++P) {
1598 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001599 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001600 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1601 PE = Proto->protocol_end(); P != PE; ++P)
1602 CollectInheritedProtocols(*P, Protocols);
1603 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001604 }
1605}
1606
Jay Foad39c79802011-01-12 09:06:06 +00001607unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001608 unsigned count = 0;
1609 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001610 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1611 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001612 count += CDecl->ivar_size();
1613
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001614 // Count ivar defined in this class's implementation. This
1615 // includes synthesized ivars.
1616 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001617 count += ImplDecl->ivar_size();
1618
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001619 return count;
1620}
1621
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001622bool ASTContext::isSentinelNullExpr(const Expr *E) {
1623 if (!E)
1624 return false;
1625
1626 // nullptr_t is always treated as null.
1627 if (E->getType()->isNullPtrType()) return true;
1628
1629 if (E->getType()->isAnyPointerType() &&
1630 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1631 Expr::NPC_ValueDependentIsNull))
1632 return true;
1633
1634 // Unfortunately, __null has type 'int'.
1635 if (isa<GNUNullExpr>(E)) return true;
1636
1637 return false;
1638}
1639
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001640/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1641ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1642 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1643 I = ObjCImpls.find(D);
1644 if (I != ObjCImpls.end())
1645 return cast<ObjCImplementationDecl>(I->second);
1646 return 0;
1647}
1648/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1649ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1650 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1651 I = ObjCImpls.find(D);
1652 if (I != ObjCImpls.end())
1653 return cast<ObjCCategoryImplDecl>(I->second);
1654 return 0;
1655}
1656
1657/// \brief Set the implementation of ObjCInterfaceDecl.
1658void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1659 ObjCImplementationDecl *ImplD) {
1660 assert(IFaceD && ImplD && "Passed null params");
1661 ObjCImpls[IFaceD] = ImplD;
1662}
1663/// \brief Set the implementation of ObjCCategoryDecl.
1664void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1665 ObjCCategoryImplDecl *ImplD) {
1666 assert(CatD && ImplD && "Passed null params");
1667 ObjCImpls[CatD] = ImplD;
1668}
1669
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001670ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1671 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1672 return ID;
1673 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1674 return CD->getClassInterface();
1675 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1676 return IMD->getClassInterface();
1677
1678 return 0;
1679}
1680
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001681/// \brief Get the copy initialization expression of VarDecl,or NULL if
1682/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001683Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001684 assert(VD && "Passed null params");
1685 assert(VD->hasAttr<BlocksAttr>() &&
1686 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001687 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001688 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001689 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1690}
1691
1692/// \brief Set the copy inialization expression of a block var decl.
1693void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1694 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001695 assert(VD->hasAttr<BlocksAttr>() &&
1696 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001697 BlockVarCopyInits[VD] = Init;
1698}
1699
John McCallbcd03502009-12-07 02:54:59 +00001700TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001701 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001702 if (!DataSize)
1703 DataSize = TypeLoc::getFullDataSizeForType(T);
1704 else
1705 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001706 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001707
John McCallbcd03502009-12-07 02:54:59 +00001708 TypeSourceInfo *TInfo =
1709 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1710 new (TInfo) TypeSourceInfo(T);
1711 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001712}
1713
John McCallbcd03502009-12-07 02:54:59 +00001714TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001715 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001716 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001717 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001718 return DI;
1719}
1720
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001721const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001722ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001723 return getObjCLayout(D, 0);
1724}
1725
1726const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001727ASTContext::getASTObjCImplementationLayout(
1728 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001729 return getObjCLayout(D->getClassInterface(), D);
1730}
1731
Chris Lattner983a8bb2007-07-13 22:13:22 +00001732//===----------------------------------------------------------------------===//
1733// Type creation/memoization methods
1734//===----------------------------------------------------------------------===//
1735
Jay Foad39c79802011-01-12 09:06:06 +00001736QualType
John McCall33ddac02011-01-19 10:06:00 +00001737ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1738 unsigned fastQuals = quals.getFastQualifiers();
1739 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001740
1741 // Check if we've already instantiated this type.
1742 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001743 ExtQuals::Profile(ID, baseType, quals);
1744 void *insertPos = 0;
1745 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1746 assert(eq->getQualifiers() == quals);
1747 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001748 }
1749
John McCall33ddac02011-01-19 10:06:00 +00001750 // If the base type is not canonical, make the appropriate canonical type.
1751 QualType canon;
1752 if (!baseType->isCanonicalUnqualified()) {
1753 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001754 canonSplit.Quals.addConsistentQualifiers(quals);
1755 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001756
1757 // Re-find the insert position.
1758 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1759 }
1760
1761 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1762 ExtQualNodes.InsertNode(eq, insertPos);
1763 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001764}
1765
Jay Foad39c79802011-01-12 09:06:06 +00001766QualType
1767ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001768 QualType CanT = getCanonicalType(T);
1769 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001770 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001771
John McCall8ccfcb52009-09-24 19:53:00 +00001772 // If we are composing extended qualifiers together, merge together
1773 // into one ExtQuals node.
1774 QualifierCollector Quals;
1775 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001776
John McCall8ccfcb52009-09-24 19:53:00 +00001777 // If this type already has an address space specified, it cannot get
1778 // another one.
1779 assert(!Quals.hasAddressSpace() &&
1780 "Type cannot be in multiple addr spaces!");
1781 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001782
John McCall8ccfcb52009-09-24 19:53:00 +00001783 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001784}
1785
Chris Lattnerd60183d2009-02-18 22:53:11 +00001786QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001787 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001788 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001789 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001790 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001791
John McCall53fa7142010-12-24 02:08:15 +00001792 if (const PointerType *ptr = T->getAs<PointerType>()) {
1793 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001794 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001795 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1796 return getPointerType(ResultType);
1797 }
1798 }
Mike Stump11289f42009-09-09 15:08:12 +00001799
John McCall8ccfcb52009-09-24 19:53:00 +00001800 // If we are composing extended qualifiers together, merge together
1801 // into one ExtQuals node.
1802 QualifierCollector Quals;
1803 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001804
John McCall8ccfcb52009-09-24 19:53:00 +00001805 // If this type already has an ObjCGC specified, it cannot get
1806 // another one.
1807 assert(!Quals.hasObjCGCAttr() &&
1808 "Type cannot have multiple ObjCGCs!");
1809 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001810
John McCall8ccfcb52009-09-24 19:53:00 +00001811 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001812}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001813
John McCall4f5019e2010-12-19 02:44:49 +00001814const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1815 FunctionType::ExtInfo Info) {
1816 if (T->getExtInfo() == Info)
1817 return T;
1818
1819 QualType Result;
1820 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1821 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1822 } else {
1823 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1824 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1825 EPI.ExtInfo = Info;
1826 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1827 FPT->getNumArgs(), EPI);
1828 }
1829
1830 return cast<FunctionType>(Result.getTypePtr());
1831}
1832
Chris Lattnerc6395932007-06-22 20:56:16 +00001833/// getComplexType - Return the uniqued reference to the type for a complex
1834/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001835QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001836 // Unique pointers, to guarantee there is only one pointer of a particular
1837 // structure.
1838 llvm::FoldingSetNodeID ID;
1839 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001840
Chris Lattnerc6395932007-06-22 20:56:16 +00001841 void *InsertPos = 0;
1842 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1843 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001844
Chris Lattnerc6395932007-06-22 20:56:16 +00001845 // If the pointee type isn't canonical, this won't be a canonical type either,
1846 // so fill in the canonical type field.
1847 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001848 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001849 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001850
Chris Lattnerc6395932007-06-22 20:56:16 +00001851 // Get the new insert position for the node we care about.
1852 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001853 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001854 }
John McCall90d1c2d2009-09-24 23:30:46 +00001855 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001856 Types.push_back(New);
1857 ComplexTypes.InsertNode(New, InsertPos);
1858 return QualType(New, 0);
1859}
1860
Chris Lattner970e54e2006-11-12 00:37:36 +00001861/// getPointerType - Return the uniqued reference to the type for a pointer to
1862/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001863QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001864 // Unique pointers, to guarantee there is only one pointer of a particular
1865 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001866 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001867 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001868
Chris Lattner67521df2007-01-27 01:29:36 +00001869 void *InsertPos = 0;
1870 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001871 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001872
Chris Lattner7ccecb92006-11-12 08:50:50 +00001873 // If the pointee type isn't canonical, this won't be a canonical type either,
1874 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001875 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001876 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001877 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001878
Chris Lattner67521df2007-01-27 01:29:36 +00001879 // Get the new insert position for the node we care about.
1880 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001881 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001882 }
John McCall90d1c2d2009-09-24 23:30:46 +00001883 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001884 Types.push_back(New);
1885 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001886 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001887}
1888
Mike Stump11289f42009-09-09 15:08:12 +00001889/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001890/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001891QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001892 assert(T->isFunctionType() && "block of function types only");
1893 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001894 // structure.
1895 llvm::FoldingSetNodeID ID;
1896 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001897
Steve Naroffec33ed92008-08-27 16:04:49 +00001898 void *InsertPos = 0;
1899 if (BlockPointerType *PT =
1900 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1901 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001902
1903 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001904 // type either so fill in the canonical type field.
1905 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001906 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001907 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001908
Steve Naroffec33ed92008-08-27 16:04:49 +00001909 // Get the new insert position for the node we care about.
1910 BlockPointerType *NewIP =
1911 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001912 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001913 }
John McCall90d1c2d2009-09-24 23:30:46 +00001914 BlockPointerType *New
1915 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001916 Types.push_back(New);
1917 BlockPointerTypes.InsertNode(New, InsertPos);
1918 return QualType(New, 0);
1919}
1920
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001921/// getLValueReferenceType - Return the uniqued reference to the type for an
1922/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001923QualType
1924ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001925 assert(getCanonicalType(T) != OverloadTy &&
1926 "Unresolved overloaded function type");
1927
Bill Wendling3708c182007-05-27 10:15:43 +00001928 // Unique pointers, to guarantee there is only one pointer of a particular
1929 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001930 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001931 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001932
1933 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001934 if (LValueReferenceType *RT =
1935 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001936 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001937
John McCallfc93cf92009-10-22 22:37:11 +00001938 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1939
Bill Wendling3708c182007-05-27 10:15:43 +00001940 // If the referencee type isn't canonical, this won't be a canonical type
1941 // either, so fill in the canonical type field.
1942 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001943 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1944 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1945 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001946
Bill Wendling3708c182007-05-27 10:15:43 +00001947 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001948 LValueReferenceType *NewIP =
1949 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001950 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001951 }
1952
John McCall90d1c2d2009-09-24 23:30:46 +00001953 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001954 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1955 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001956 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001957 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001958
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001959 return QualType(New, 0);
1960}
1961
1962/// getRValueReferenceType - Return the uniqued reference to the type for an
1963/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001964QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001965 // Unique pointers, to guarantee there is only one pointer of a particular
1966 // structure.
1967 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001968 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001969
1970 void *InsertPos = 0;
1971 if (RValueReferenceType *RT =
1972 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1973 return QualType(RT, 0);
1974
John McCallfc93cf92009-10-22 22:37:11 +00001975 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1976
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001977 // If the referencee type isn't canonical, this won't be a canonical type
1978 // either, so fill in the canonical type field.
1979 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001980 if (InnerRef || !T.isCanonical()) {
1981 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1982 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001983
1984 // Get the new insert position for the node we care about.
1985 RValueReferenceType *NewIP =
1986 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001987 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001988 }
1989
John McCall90d1c2d2009-09-24 23:30:46 +00001990 RValueReferenceType *New
1991 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001992 Types.push_back(New);
1993 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001994 return QualType(New, 0);
1995}
1996
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001997/// getMemberPointerType - Return the uniqued reference to the type for a
1998/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001999QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002000 // Unique pointers, to guarantee there is only one pointer of a particular
2001 // structure.
2002 llvm::FoldingSetNodeID ID;
2003 MemberPointerType::Profile(ID, T, Cls);
2004
2005 void *InsertPos = 0;
2006 if (MemberPointerType *PT =
2007 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2008 return QualType(PT, 0);
2009
2010 // If the pointee or class type isn't canonical, this won't be a canonical
2011 // type either, so fill in the canonical type field.
2012 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002013 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002014 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2015
2016 // Get the new insert position for the node we care about.
2017 MemberPointerType *NewIP =
2018 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002019 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002020 }
John McCall90d1c2d2009-09-24 23:30:46 +00002021 MemberPointerType *New
2022 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002023 Types.push_back(New);
2024 MemberPointerTypes.InsertNode(New, InsertPos);
2025 return QualType(New, 0);
2026}
2027
Mike Stump11289f42009-09-09 15:08:12 +00002028/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002029/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002030QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002031 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002032 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002033 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002034 assert((EltTy->isDependentType() ||
2035 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002036 "Constant array of VLAs is illegal!");
2037
Chris Lattnere2df3f92009-05-13 04:12:56 +00002038 // Convert the array size into a canonical width matching the pointer size for
2039 // the target.
2040 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002041 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002042 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002043
Chris Lattner23b7eb62007-06-15 23:05:46 +00002044 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002045 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Chris Lattner36f8e652007-01-27 08:31:04 +00002047 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002048 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002049 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002050 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002051
John McCall33ddac02011-01-19 10:06:00 +00002052 // If the element type isn't canonical or has qualifiers, this won't
2053 // be a canonical type either, so fill in the canonical type field.
2054 QualType Canon;
2055 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2056 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002057 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002058 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002059 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002060
Chris Lattner36f8e652007-01-27 08:31:04 +00002061 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002062 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002063 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002064 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
John McCall90d1c2d2009-09-24 23:30:46 +00002067 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002068 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002069 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002070 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002071 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002072}
2073
John McCall06549462011-01-18 08:40:38 +00002074/// getVariableArrayDecayedType - Turns the given type, which may be
2075/// variably-modified, into the corresponding type with all the known
2076/// sizes replaced with [*].
2077QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2078 // Vastly most common case.
2079 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002080
John McCall06549462011-01-18 08:40:38 +00002081 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002082
John McCall06549462011-01-18 08:40:38 +00002083 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002084 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002085 switch (ty->getTypeClass()) {
2086#define TYPE(Class, Base)
2087#define ABSTRACT_TYPE(Class, Base)
2088#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2089#include "clang/AST/TypeNodes.def"
2090 llvm_unreachable("didn't desugar past all non-canonical types?");
2091
2092 // These types should never be variably-modified.
2093 case Type::Builtin:
2094 case Type::Complex:
2095 case Type::Vector:
2096 case Type::ExtVector:
2097 case Type::DependentSizedExtVector:
2098 case Type::ObjCObject:
2099 case Type::ObjCInterface:
2100 case Type::ObjCObjectPointer:
2101 case Type::Record:
2102 case Type::Enum:
2103 case Type::UnresolvedUsing:
2104 case Type::TypeOfExpr:
2105 case Type::TypeOf:
2106 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002107 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002108 case Type::DependentName:
2109 case Type::InjectedClassName:
2110 case Type::TemplateSpecialization:
2111 case Type::DependentTemplateSpecialization:
2112 case Type::TemplateTypeParm:
2113 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002114 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002115 case Type::PackExpansion:
2116 llvm_unreachable("type should never be variably-modified");
2117
2118 // These types can be variably-modified but should never need to
2119 // further decay.
2120 case Type::FunctionNoProto:
2121 case Type::FunctionProto:
2122 case Type::BlockPointer:
2123 case Type::MemberPointer:
2124 return type;
2125
2126 // These types can be variably-modified. All these modifications
2127 // preserve structure except as noted by comments.
2128 // TODO: if we ever care about optimizing VLAs, there are no-op
2129 // optimizations available here.
2130 case Type::Pointer:
2131 result = getPointerType(getVariableArrayDecayedType(
2132 cast<PointerType>(ty)->getPointeeType()));
2133 break;
2134
2135 case Type::LValueReference: {
2136 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2137 result = getLValueReferenceType(
2138 getVariableArrayDecayedType(lv->getPointeeType()),
2139 lv->isSpelledAsLValue());
2140 break;
2141 }
2142
2143 case Type::RValueReference: {
2144 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2145 result = getRValueReferenceType(
2146 getVariableArrayDecayedType(lv->getPointeeType()));
2147 break;
2148 }
2149
Eli Friedman0dfb8892011-10-06 23:00:33 +00002150 case Type::Atomic: {
2151 const AtomicType *at = cast<AtomicType>(ty);
2152 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2153 break;
2154 }
2155
John McCall06549462011-01-18 08:40:38 +00002156 case Type::ConstantArray: {
2157 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2158 result = getConstantArrayType(
2159 getVariableArrayDecayedType(cat->getElementType()),
2160 cat->getSize(),
2161 cat->getSizeModifier(),
2162 cat->getIndexTypeCVRQualifiers());
2163 break;
2164 }
2165
2166 case Type::DependentSizedArray: {
2167 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2168 result = getDependentSizedArrayType(
2169 getVariableArrayDecayedType(dat->getElementType()),
2170 dat->getSizeExpr(),
2171 dat->getSizeModifier(),
2172 dat->getIndexTypeCVRQualifiers(),
2173 dat->getBracketsRange());
2174 break;
2175 }
2176
2177 // Turn incomplete types into [*] types.
2178 case Type::IncompleteArray: {
2179 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2180 result = getVariableArrayType(
2181 getVariableArrayDecayedType(iat->getElementType()),
2182 /*size*/ 0,
2183 ArrayType::Normal,
2184 iat->getIndexTypeCVRQualifiers(),
2185 SourceRange());
2186 break;
2187 }
2188
2189 // Turn VLA types into [*] types.
2190 case Type::VariableArray: {
2191 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2192 result = getVariableArrayType(
2193 getVariableArrayDecayedType(vat->getElementType()),
2194 /*size*/ 0,
2195 ArrayType::Star,
2196 vat->getIndexTypeCVRQualifiers(),
2197 vat->getBracketsRange());
2198 break;
2199 }
2200 }
2201
2202 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002203 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002204}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002205
Steve Naroffcadebd02007-08-30 18:14:25 +00002206/// getVariableArrayType - Returns a non-unique reference to the type for a
2207/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002208QualType ASTContext::getVariableArrayType(QualType EltTy,
2209 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002210 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002211 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002212 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002213 // Since we don't unique expressions, it isn't possible to unique VLA's
2214 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002215 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002216
John McCall33ddac02011-01-19 10:06:00 +00002217 // Be sure to pull qualifiers off the element type.
2218 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2219 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002220 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002221 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002222 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002223 }
2224
John McCall90d1c2d2009-09-24 23:30:46 +00002225 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002226 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002227
2228 VariableArrayTypes.push_back(New);
2229 Types.push_back(New);
2230 return QualType(New, 0);
2231}
2232
Douglas Gregor4619e432008-12-05 23:32:09 +00002233/// getDependentSizedArrayType - Returns a non-unique reference to
2234/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002235/// type.
John McCall33ddac02011-01-19 10:06:00 +00002236QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2237 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002238 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002239 unsigned elementTypeQuals,
2240 SourceRange brackets) const {
2241 assert((!numElements || numElements->isTypeDependent() ||
2242 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002243 "Size must be type- or value-dependent!");
2244
John McCall33ddac02011-01-19 10:06:00 +00002245 // Dependently-sized array types that do not have a specified number
2246 // of elements will have their sizes deduced from a dependent
2247 // initializer. We do no canonicalization here at all, which is okay
2248 // because they can't be used in most locations.
2249 if (!numElements) {
2250 DependentSizedArrayType *newType
2251 = new (*this, TypeAlignment)
2252 DependentSizedArrayType(*this, elementType, QualType(),
2253 numElements, ASM, elementTypeQuals,
2254 brackets);
2255 Types.push_back(newType);
2256 return QualType(newType, 0);
2257 }
2258
2259 // Otherwise, we actually build a new type every time, but we
2260 // also build a canonical type.
2261
2262 SplitQualType canonElementType = getCanonicalType(elementType).split();
2263
2264 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002265 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002266 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002267 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002268 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002269
John McCall33ddac02011-01-19 10:06:00 +00002270 // Look for an existing type with these properties.
2271 DependentSizedArrayType *canonTy =
2272 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002273
John McCall33ddac02011-01-19 10:06:00 +00002274 // If we don't have one, build one.
2275 if (!canonTy) {
2276 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002277 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002278 QualType(), numElements, ASM, elementTypeQuals,
2279 brackets);
2280 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2281 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002282 }
2283
John McCall33ddac02011-01-19 10:06:00 +00002284 // Apply qualifiers from the element type to the array.
2285 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002286 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002287
John McCall33ddac02011-01-19 10:06:00 +00002288 // If we didn't need extra canonicalization for the element type,
2289 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002290 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002291 return canon;
2292
2293 // Otherwise, we need to build a type which follows the spelling
2294 // of the element type.
2295 DependentSizedArrayType *sugaredType
2296 = new (*this, TypeAlignment)
2297 DependentSizedArrayType(*this, elementType, canon, numElements,
2298 ASM, elementTypeQuals, brackets);
2299 Types.push_back(sugaredType);
2300 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002301}
2302
John McCall33ddac02011-01-19 10:06:00 +00002303QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002304 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002305 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002306 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002307 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002308
John McCall33ddac02011-01-19 10:06:00 +00002309 void *insertPos = 0;
2310 if (IncompleteArrayType *iat =
2311 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2312 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002313
2314 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002315 // either, so fill in the canonical type field. We also have to pull
2316 // qualifiers off the element type.
2317 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002318
John McCall33ddac02011-01-19 10:06:00 +00002319 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2320 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002321 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002322 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002323 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002324
2325 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002326 IncompleteArrayType *existing =
2327 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2328 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002329 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002330
John McCall33ddac02011-01-19 10:06:00 +00002331 IncompleteArrayType *newType = new (*this, TypeAlignment)
2332 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002333
John McCall33ddac02011-01-19 10:06:00 +00002334 IncompleteArrayTypes.InsertNode(newType, insertPos);
2335 Types.push_back(newType);
2336 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002337}
2338
Steve Naroff91fcddb2007-07-18 18:00:27 +00002339/// getVectorType - Return the unique reference to a vector type of
2340/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002341QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002342 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002343 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002344
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002345 // Check if we've already instantiated a vector of this type.
2346 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002347 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002348
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002349 void *InsertPos = 0;
2350 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2351 return QualType(VTP, 0);
2352
2353 // If the element type isn't canonical, this won't be a canonical type either,
2354 // so fill in the canonical type field.
2355 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002356 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002357 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002358
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002359 // Get the new insert position for the node we care about.
2360 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002361 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002362 }
John McCall90d1c2d2009-09-24 23:30:46 +00002363 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002364 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002365 VectorTypes.InsertNode(New, InsertPos);
2366 Types.push_back(New);
2367 return QualType(New, 0);
2368}
2369
Nate Begemance4d7fc2008-04-18 23:10:10 +00002370/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002371/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002372QualType
2373ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002374 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002375
Steve Naroff91fcddb2007-07-18 18:00:27 +00002376 // Check if we've already instantiated a vector of this type.
2377 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002378 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002379 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002380 void *InsertPos = 0;
2381 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2382 return QualType(VTP, 0);
2383
2384 // If the element type isn't canonical, this won't be a canonical type either,
2385 // so fill in the canonical type field.
2386 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002387 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002388 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002389
Steve Naroff91fcddb2007-07-18 18:00:27 +00002390 // Get the new insert position for the node we care about.
2391 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002392 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002393 }
John McCall90d1c2d2009-09-24 23:30:46 +00002394 ExtVectorType *New = new (*this, TypeAlignment)
2395 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002396 VectorTypes.InsertNode(New, InsertPos);
2397 Types.push_back(New);
2398 return QualType(New, 0);
2399}
2400
Jay Foad39c79802011-01-12 09:06:06 +00002401QualType
2402ASTContext::getDependentSizedExtVectorType(QualType vecType,
2403 Expr *SizeExpr,
2404 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002405 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002406 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002407 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002408
Douglas Gregor352169a2009-07-31 03:54:25 +00002409 void *InsertPos = 0;
2410 DependentSizedExtVectorType *Canon
2411 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2412 DependentSizedExtVectorType *New;
2413 if (Canon) {
2414 // We already have a canonical version of this array type; use it as
2415 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002416 New = new (*this, TypeAlignment)
2417 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2418 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002419 } else {
2420 QualType CanonVecTy = getCanonicalType(vecType);
2421 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002422 New = new (*this, TypeAlignment)
2423 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2424 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002425
2426 DependentSizedExtVectorType *CanonCheck
2427 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2428 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2429 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002430 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2431 } else {
2432 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2433 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002434 New = new (*this, TypeAlignment)
2435 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002436 }
2437 }
Mike Stump11289f42009-09-09 15:08:12 +00002438
Douglas Gregor758a8692009-06-17 21:51:59 +00002439 Types.push_back(New);
2440 return QualType(New, 0);
2441}
2442
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002443/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002444///
Jay Foad39c79802011-01-12 09:06:06 +00002445QualType
2446ASTContext::getFunctionNoProtoType(QualType ResultTy,
2447 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002448 const CallingConv DefaultCC = Info.getCC();
2449 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2450 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002451 // Unique functions, to guarantee there is only one function of a particular
2452 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002453 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002454 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002455
Chris Lattner47955de2007-01-27 08:37:20 +00002456 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002457 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002458 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002459 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002460
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002461 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002462 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002463 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002464 Canonical =
2465 getFunctionNoProtoType(getCanonicalType(ResultTy),
2466 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002467
Chris Lattner47955de2007-01-27 08:37:20 +00002468 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002469 FunctionNoProtoType *NewIP =
2470 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002471 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002472 }
Mike Stump11289f42009-09-09 15:08:12 +00002473
Roman Divacky65b88cd2011-03-01 17:40:53 +00002474 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002475 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002476 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002477 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002478 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002479 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002480}
2481
2482/// getFunctionType - Return a normal function type with a typed argument
2483/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002484QualType
2485ASTContext::getFunctionType(QualType ResultTy,
2486 const QualType *ArgArray, unsigned NumArgs,
2487 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002488 // Unique functions, to guarantee there is only one function of a particular
2489 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002490 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002491 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002492
2493 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002494 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002495 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002496 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002497
2498 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002499 bool isCanonical =
2500 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2501 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002502 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002503 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002504 isCanonical = false;
2505
Roman Divacky65b88cd2011-03-01 17:40:53 +00002506 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2507 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2508 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002509
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002510 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002511 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002512 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002513 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002514 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002515 CanonicalArgs.reserve(NumArgs);
2516 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002517 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002518
John McCalldb40c7f2010-12-14 08:05:40 +00002519 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002520 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002521 CanonicalEPI.ExceptionSpecType = EST_None;
2522 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002523 CanonicalEPI.ExtInfo
2524 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2525
Chris Lattner76a00cf2008-04-06 22:59:24 +00002526 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002527 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002528 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002529
Chris Lattnerfd4de792007-01-27 01:15:32 +00002530 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002531 FunctionProtoType *NewIP =
2532 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002533 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002534 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002535
John McCall31168b02011-06-15 23:02:42 +00002536 // FunctionProtoType objects are allocated with extra bytes after
2537 // them for three variable size arrays at the end:
2538 // - parameter types
2539 // - exception types
2540 // - consumed-arguments flags
2541 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002542 // expression, or information used to resolve the exception
2543 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002544 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002545 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002546 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002547 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002548 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002549 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002550 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002551 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002552 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2553 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002554 }
John McCall31168b02011-06-15 23:02:42 +00002555 if (EPI.ConsumedArguments)
2556 Size += NumArgs * sizeof(bool);
2557
John McCalldb40c7f2010-12-14 08:05:40 +00002558 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002559 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2560 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002561 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002562 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002563 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002564 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002565}
Chris Lattneref51c202006-11-10 07:17:23 +00002566
John McCalle78aac42010-03-10 03:28:59 +00002567#ifndef NDEBUG
2568static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2569 if (!isa<CXXRecordDecl>(D)) return false;
2570 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2571 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2572 return true;
2573 if (RD->getDescribedClassTemplate() &&
2574 !isa<ClassTemplateSpecializationDecl>(RD))
2575 return true;
2576 return false;
2577}
2578#endif
2579
2580/// getInjectedClassNameType - Return the unique reference to the
2581/// injected class name type for the specified templated declaration.
2582QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002583 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002584 assert(NeedsInjectedClassNameType(Decl));
2585 if (Decl->TypeForDecl) {
2586 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002587 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002588 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2589 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2590 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2591 } else {
John McCall424cec92011-01-19 06:33:43 +00002592 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002593 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002594 Decl->TypeForDecl = newType;
2595 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002596 }
2597 return QualType(Decl->TypeForDecl, 0);
2598}
2599
Douglas Gregor83a586e2008-04-13 21:07:44 +00002600/// getTypeDeclType - Return the unique reference to the type for the
2601/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002602QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002603 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002604 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002605
Richard Smithdda56e42011-04-15 14:24:37 +00002606 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002607 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002608
John McCall96f0b5f2010-03-10 06:48:02 +00002609 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2610 "Template type parameter types are always available.");
2611
John McCall81e38502010-02-16 03:57:14 +00002612 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002613 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002614 "struct/union has previous declaration");
2615 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002616 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002617 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002618 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002619 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002620 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002621 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002622 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002623 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2624 Decl->TypeForDecl = newType;
2625 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002626 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002627 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002628
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002629 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002630}
2631
Chris Lattner32d920b2007-01-26 02:01:53 +00002632/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002633/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002634QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002635ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2636 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002637 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002638
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002639 if (Canonical.isNull())
2640 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002641 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002642 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002643 Decl->TypeForDecl = newType;
2644 Types.push_back(newType);
2645 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002646}
2647
Jay Foad39c79802011-01-12 09:06:06 +00002648QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002649 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2650
Douglas Gregorec9fd132012-01-14 16:38:05 +00002651 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002652 if (PrevDecl->TypeForDecl)
2653 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2654
John McCall424cec92011-01-19 06:33:43 +00002655 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2656 Decl->TypeForDecl = newType;
2657 Types.push_back(newType);
2658 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002659}
2660
Jay Foad39c79802011-01-12 09:06:06 +00002661QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002662 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2663
Douglas Gregorec9fd132012-01-14 16:38:05 +00002664 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002665 if (PrevDecl->TypeForDecl)
2666 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2667
John McCall424cec92011-01-19 06:33:43 +00002668 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2669 Decl->TypeForDecl = newType;
2670 Types.push_back(newType);
2671 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002672}
2673
John McCall81904512011-01-06 01:58:22 +00002674QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2675 QualType modifiedType,
2676 QualType equivalentType) {
2677 llvm::FoldingSetNodeID id;
2678 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2679
2680 void *insertPos = 0;
2681 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2682 if (type) return QualType(type, 0);
2683
2684 QualType canon = getCanonicalType(equivalentType);
2685 type = new (*this, TypeAlignment)
2686 AttributedType(canon, attrKind, modifiedType, equivalentType);
2687
2688 Types.push_back(type);
2689 AttributedTypes.InsertNode(type, insertPos);
2690
2691 return QualType(type, 0);
2692}
2693
2694
John McCallcebee162009-10-18 09:09:24 +00002695/// \brief Retrieve a substitution-result type.
2696QualType
2697ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002698 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002699 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002700 && "replacement types must always be canonical");
2701
2702 llvm::FoldingSetNodeID ID;
2703 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2704 void *InsertPos = 0;
2705 SubstTemplateTypeParmType *SubstParm
2706 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2707
2708 if (!SubstParm) {
2709 SubstParm = new (*this, TypeAlignment)
2710 SubstTemplateTypeParmType(Parm, Replacement);
2711 Types.push_back(SubstParm);
2712 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2713 }
2714
2715 return QualType(SubstParm, 0);
2716}
2717
Douglas Gregorada4b792011-01-14 02:55:32 +00002718/// \brief Retrieve a
2719QualType ASTContext::getSubstTemplateTypeParmPackType(
2720 const TemplateTypeParmType *Parm,
2721 const TemplateArgument &ArgPack) {
2722#ifndef NDEBUG
2723 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2724 PEnd = ArgPack.pack_end();
2725 P != PEnd; ++P) {
2726 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2727 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2728 }
2729#endif
2730
2731 llvm::FoldingSetNodeID ID;
2732 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2733 void *InsertPos = 0;
2734 if (SubstTemplateTypeParmPackType *SubstParm
2735 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2736 return QualType(SubstParm, 0);
2737
2738 QualType Canon;
2739 if (!Parm->isCanonicalUnqualified()) {
2740 Canon = getCanonicalType(QualType(Parm, 0));
2741 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2742 ArgPack);
2743 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2744 }
2745
2746 SubstTemplateTypeParmPackType *SubstParm
2747 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2748 ArgPack);
2749 Types.push_back(SubstParm);
2750 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2751 return QualType(SubstParm, 0);
2752}
2753
Douglas Gregoreff93e02009-02-05 23:33:38 +00002754/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002755/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002756/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002757QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002758 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002759 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002760 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002761 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002762 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002763 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002764 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2765
2766 if (TypeParm)
2767 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002768
Chandler Carruth08836322011-05-01 00:51:33 +00002769 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002770 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002771 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002772
2773 TemplateTypeParmType *TypeCheck
2774 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2775 assert(!TypeCheck && "Template type parameter canonical type broken");
2776 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002777 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002778 TypeParm = new (*this, TypeAlignment)
2779 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002780
2781 Types.push_back(TypeParm);
2782 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2783
2784 return QualType(TypeParm, 0);
2785}
2786
John McCalle78aac42010-03-10 03:28:59 +00002787TypeSourceInfo *
2788ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2789 SourceLocation NameLoc,
2790 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002791 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002792 assert(!Name.getAsDependentTemplateName() &&
2793 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002794 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002795
2796 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2797 TemplateSpecializationTypeLoc TL
2798 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002799 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002800 TL.setTemplateNameLoc(NameLoc);
2801 TL.setLAngleLoc(Args.getLAngleLoc());
2802 TL.setRAngleLoc(Args.getRAngleLoc());
2803 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2804 TL.setArgLocInfo(i, Args[i].getLocInfo());
2805 return DI;
2806}
2807
Mike Stump11289f42009-09-09 15:08:12 +00002808QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002809ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002810 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002811 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002812 assert(!Template.getAsDependentTemplateName() &&
2813 "No dependent template names here!");
2814
John McCall6b51f282009-11-23 01:53:49 +00002815 unsigned NumArgs = Args.size();
2816
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002817 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002818 ArgVec.reserve(NumArgs);
2819 for (unsigned i = 0; i != NumArgs; ++i)
2820 ArgVec.push_back(Args[i].getArgument());
2821
John McCall2408e322010-04-27 00:57:59 +00002822 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002823 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002824}
2825
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002826#ifndef NDEBUG
2827static bool hasAnyPackExpansions(const TemplateArgument *Args,
2828 unsigned NumArgs) {
2829 for (unsigned I = 0; I != NumArgs; ++I)
2830 if (Args[I].isPackExpansion())
2831 return true;
2832
2833 return true;
2834}
2835#endif
2836
John McCall0ad16662009-10-29 08:12:44 +00002837QualType
2838ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002839 const TemplateArgument *Args,
2840 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002841 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002842 assert(!Template.getAsDependentTemplateName() &&
2843 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002844 // Look through qualified template names.
2845 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2846 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002847
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002848 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002849 Template.getAsTemplateDecl() &&
2850 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002851 QualType CanonType;
2852 if (!Underlying.isNull())
2853 CanonType = getCanonicalType(Underlying);
2854 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002855 // We can get here with an alias template when the specialization contains
2856 // a pack expansion that does not match up with a parameter pack.
2857 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2858 "Caller must compute aliased type");
2859 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002860 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2861 NumArgs);
2862 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002863
Douglas Gregora8e02e72009-07-28 23:00:59 +00002864 // Allocate the (non-canonical) template specialization type, but don't
2865 // try to unique it: these types typically have location information that
2866 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002867 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2868 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002869 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002870 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002871 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002872 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2873 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002874
Douglas Gregor8bf42052009-02-09 18:46:07 +00002875 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002876 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002877}
2878
Mike Stump11289f42009-09-09 15:08:12 +00002879QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002880ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2881 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002882 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002883 assert(!Template.getAsDependentTemplateName() &&
2884 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002885
Douglas Gregore29139c2011-03-03 17:04:51 +00002886 // Look through qualified template names.
2887 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2888 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002889
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002890 // Build the canonical template specialization type.
2891 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002892 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002893 CanonArgs.reserve(NumArgs);
2894 for (unsigned I = 0; I != NumArgs; ++I)
2895 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2896
2897 // Determine whether this canonical template specialization type already
2898 // exists.
2899 llvm::FoldingSetNodeID ID;
2900 TemplateSpecializationType::Profile(ID, CanonTemplate,
2901 CanonArgs.data(), NumArgs, *this);
2902
2903 void *InsertPos = 0;
2904 TemplateSpecializationType *Spec
2905 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2906
2907 if (!Spec) {
2908 // Allocate a new canonical template specialization type.
2909 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2910 sizeof(TemplateArgument) * NumArgs),
2911 TypeAlignment);
2912 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2913 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002914 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002915 Types.push_back(Spec);
2916 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2917 }
2918
2919 assert(Spec->isDependentType() &&
2920 "Non-dependent template-id type must have a canonical type");
2921 return QualType(Spec, 0);
2922}
2923
2924QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002925ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2926 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002927 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002928 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002929 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002930
2931 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002932 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002933 if (T)
2934 return QualType(T, 0);
2935
Douglas Gregorc42075a2010-02-04 18:10:26 +00002936 QualType Canon = NamedType;
2937 if (!Canon.isCanonical()) {
2938 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002939 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2940 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002941 (void)CheckT;
2942 }
2943
Abramo Bagnara6150c882010-05-11 21:36:43 +00002944 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002945 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002946 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002947 return QualType(T, 0);
2948}
2949
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002950QualType
Jay Foad39c79802011-01-12 09:06:06 +00002951ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002952 llvm::FoldingSetNodeID ID;
2953 ParenType::Profile(ID, InnerType);
2954
2955 void *InsertPos = 0;
2956 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2957 if (T)
2958 return QualType(T, 0);
2959
2960 QualType Canon = InnerType;
2961 if (!Canon.isCanonical()) {
2962 Canon = getCanonicalType(InnerType);
2963 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2964 assert(!CheckT && "Paren canonical type broken");
2965 (void)CheckT;
2966 }
2967
2968 T = new (*this) ParenType(InnerType, Canon);
2969 Types.push_back(T);
2970 ParenTypes.InsertNode(T, InsertPos);
2971 return QualType(T, 0);
2972}
2973
Douglas Gregor02085352010-03-31 20:19:30 +00002974QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2975 NestedNameSpecifier *NNS,
2976 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002977 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002978 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2979
2980 if (Canon.isNull()) {
2981 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002982 ElaboratedTypeKeyword CanonKeyword = Keyword;
2983 if (Keyword == ETK_None)
2984 CanonKeyword = ETK_Typename;
2985
2986 if (CanonNNS != NNS || CanonKeyword != Keyword)
2987 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002988 }
2989
2990 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002991 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002992
2993 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002994 DependentNameType *T
2995 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002996 if (T)
2997 return QualType(T, 0);
2998
Douglas Gregor02085352010-03-31 20:19:30 +00002999 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003000 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003001 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003002 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003003}
3004
Mike Stump11289f42009-09-09 15:08:12 +00003005QualType
John McCallc392f372010-06-11 00:33:02 +00003006ASTContext::getDependentTemplateSpecializationType(
3007 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003008 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003009 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003010 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003011 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003012 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003013 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3014 ArgCopy.push_back(Args[I].getArgument());
3015 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3016 ArgCopy.size(),
3017 ArgCopy.data());
3018}
3019
3020QualType
3021ASTContext::getDependentTemplateSpecializationType(
3022 ElaboratedTypeKeyword Keyword,
3023 NestedNameSpecifier *NNS,
3024 const IdentifierInfo *Name,
3025 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003026 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003027 assert((!NNS || NNS->isDependent()) &&
3028 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003029
Douglas Gregorc42075a2010-02-04 18:10:26 +00003030 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003031 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3032 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003033
3034 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003035 DependentTemplateSpecializationType *T
3036 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003037 if (T)
3038 return QualType(T, 0);
3039
John McCallc392f372010-06-11 00:33:02 +00003040 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003041
John McCallc392f372010-06-11 00:33:02 +00003042 ElaboratedTypeKeyword CanonKeyword = Keyword;
3043 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3044
3045 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003046 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003047 for (unsigned I = 0; I != NumArgs; ++I) {
3048 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3049 if (!CanonArgs[I].structurallyEquals(Args[I]))
3050 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003051 }
3052
John McCallc392f372010-06-11 00:33:02 +00003053 QualType Canon;
3054 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3055 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3056 Name, NumArgs,
3057 CanonArgs.data());
3058
3059 // Find the insert position again.
3060 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3061 }
3062
3063 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3064 sizeof(TemplateArgument) * NumArgs),
3065 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003066 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003067 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003068 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003069 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003070 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003071}
3072
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003073QualType ASTContext::getPackExpansionType(QualType Pattern,
3074 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003075 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003076 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003077
3078 assert(Pattern->containsUnexpandedParameterPack() &&
3079 "Pack expansions must expand one or more parameter packs");
3080 void *InsertPos = 0;
3081 PackExpansionType *T
3082 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3083 if (T)
3084 return QualType(T, 0);
3085
3086 QualType Canon;
3087 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003088 Canon = getCanonicalType(Pattern);
3089 // The canonical type might not contain an unexpanded parameter pack, if it
3090 // contains an alias template specialization which ignores one of its
3091 // parameters.
3092 if (Canon->containsUnexpandedParameterPack()) {
3093 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003094
Richard Smith68eea502012-07-16 00:20:35 +00003095 // Find the insert position again, in case we inserted an element into
3096 // PackExpansionTypes and invalidated our insert position.
3097 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3098 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003099 }
3100
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003101 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003102 Types.push_back(T);
3103 PackExpansionTypes.InsertNode(T, InsertPos);
3104 return QualType(T, 0);
3105}
3106
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003107/// CmpProtocolNames - Comparison predicate for sorting protocols
3108/// alphabetically.
3109static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3110 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003111 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003112}
3113
John McCall8b07ec22010-05-15 11:32:37 +00003114static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003115 unsigned NumProtocols) {
3116 if (NumProtocols == 0) return true;
3117
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003118 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3119 return false;
3120
John McCallfc93cf92009-10-22 22:37:11 +00003121 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003122 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3123 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003124 return false;
3125 return true;
3126}
3127
3128static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003129 unsigned &NumProtocols) {
3130 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003131
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003132 // Sort protocols, keyed by name.
3133 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3134
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003135 // Canonicalize.
3136 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3137 Protocols[I] = Protocols[I]->getCanonicalDecl();
3138
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003139 // Remove duplicates.
3140 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3141 NumProtocols = ProtocolsEnd-Protocols;
3142}
3143
John McCall8b07ec22010-05-15 11:32:37 +00003144QualType ASTContext::getObjCObjectType(QualType BaseType,
3145 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003146 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003147 // If the base type is an interface and there aren't any protocols
3148 // to add, then the interface type will do just fine.
3149 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3150 return BaseType;
3151
3152 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003153 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003154 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003155 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003156 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3157 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003158
John McCall8b07ec22010-05-15 11:32:37 +00003159 // Build the canonical type, which has the canonical base type and
3160 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003161 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003162 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3163 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3164 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003165 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003166 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003167 unsigned UniqueCount = NumProtocols;
3168
John McCallfc93cf92009-10-22 22:37:11 +00003169 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003170 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3171 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003172 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003173 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3174 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003175 }
3176
3177 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003178 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3179 }
3180
3181 unsigned Size = sizeof(ObjCObjectTypeImpl);
3182 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3183 void *Mem = Allocate(Size, TypeAlignment);
3184 ObjCObjectTypeImpl *T =
3185 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3186
3187 Types.push_back(T);
3188 ObjCObjectTypes.InsertNode(T, InsertPos);
3189 return QualType(T, 0);
3190}
3191
3192/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3193/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003194QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003195 llvm::FoldingSetNodeID ID;
3196 ObjCObjectPointerType::Profile(ID, ObjectT);
3197
3198 void *InsertPos = 0;
3199 if (ObjCObjectPointerType *QT =
3200 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3201 return QualType(QT, 0);
3202
3203 // Find the canonical object type.
3204 QualType Canonical;
3205 if (!ObjectT.isCanonical()) {
3206 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3207
3208 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003209 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3210 }
3211
Douglas Gregorf85bee62010-02-08 22:59:26 +00003212 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003213 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3214 ObjCObjectPointerType *QType =
3215 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003216
Steve Narofffb4330f2009-06-17 22:40:22 +00003217 Types.push_back(QType);
3218 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003219 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003220}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003221
Douglas Gregor1c283312010-08-11 12:19:30 +00003222/// getObjCInterfaceType - Return the unique reference to the type for the
3223/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003224QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3225 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003226 if (Decl->TypeForDecl)
3227 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003228
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003229 if (PrevDecl) {
3230 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3231 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3232 return QualType(PrevDecl->TypeForDecl, 0);
3233 }
3234
Douglas Gregor7671e532011-12-16 16:34:57 +00003235 // Prefer the definition, if there is one.
3236 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3237 Decl = Def;
3238
Douglas Gregor1c283312010-08-11 12:19:30 +00003239 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3240 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3241 Decl->TypeForDecl = T;
3242 Types.push_back(T);
3243 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003244}
3245
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003246/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3247/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003248/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003249/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003250/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003251QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003252 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003253 if (tofExpr->isTypeDependent()) {
3254 llvm::FoldingSetNodeID ID;
3255 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003256
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003257 void *InsertPos = 0;
3258 DependentTypeOfExprType *Canon
3259 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3260 if (Canon) {
3261 // We already have a "canonical" version of an identical, dependent
3262 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003263 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003264 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003265 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003266 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003267 Canon
3268 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003269 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3270 toe = Canon;
3271 }
3272 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003273 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003274 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003275 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003276 Types.push_back(toe);
3277 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003278}
3279
Steve Naroffa773cd52007-08-01 18:02:17 +00003280/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3281/// TypeOfType AST's. The only motivation to unique these nodes would be
3282/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003283/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003284/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003285QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003286 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003287 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003288 Types.push_back(tot);
3289 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003290}
3291
Anders Carlssonad6bd352009-06-24 21:24:56 +00003292
Anders Carlsson81df7b82009-06-24 19:06:50 +00003293/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3294/// DecltypeType AST's. The only motivation to unique these nodes would be
3295/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003296/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003297/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003298QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003299 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003300
3301 // C++0x [temp.type]p2:
3302 // If an expression e involves a template parameter, decltype(e) denotes a
3303 // unique dependent type. Two such decltype-specifiers refer to the same
3304 // type only if their expressions are equivalent (14.5.6.1).
3305 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003306 llvm::FoldingSetNodeID ID;
3307 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003308
Douglas Gregora21f6c32009-07-30 23:36:40 +00003309 void *InsertPos = 0;
3310 DependentDecltypeType *Canon
3311 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3312 if (Canon) {
3313 // We already have a "canonical" version of an equivalent, dependent
3314 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003315 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003316 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003317 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003318 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003319 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003320 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3321 dt = Canon;
3322 }
3323 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003324 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3325 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003326 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003327 Types.push_back(dt);
3328 return QualType(dt, 0);
3329}
3330
Alexis Hunte852b102011-05-24 22:41:36 +00003331/// getUnaryTransformationType - We don't unique these, since the memory
3332/// savings are minimal and these are rare.
3333QualType ASTContext::getUnaryTransformType(QualType BaseType,
3334 QualType UnderlyingType,
3335 UnaryTransformType::UTTKind Kind)
3336 const {
3337 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003338 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3339 Kind,
3340 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003341 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003342 Types.push_back(Ty);
3343 return QualType(Ty, 0);
3344}
3345
Richard Smithb2bc2e62011-02-21 20:05:19 +00003346/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003347QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003348 void *InsertPos = 0;
3349 if (!DeducedType.isNull()) {
3350 // Look in the folding set for an existing type.
3351 llvm::FoldingSetNodeID ID;
3352 AutoType::Profile(ID, DeducedType);
3353 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3354 return QualType(AT, 0);
3355 }
3356
3357 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3358 Types.push_back(AT);
3359 if (InsertPos)
3360 AutoTypes.InsertNode(AT, InsertPos);
3361 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003362}
3363
Eli Friedman0dfb8892011-10-06 23:00:33 +00003364/// getAtomicType - Return the uniqued reference to the atomic type for
3365/// the given value type.
3366QualType ASTContext::getAtomicType(QualType T) const {
3367 // Unique pointers, to guarantee there is only one pointer of a particular
3368 // structure.
3369 llvm::FoldingSetNodeID ID;
3370 AtomicType::Profile(ID, T);
3371
3372 void *InsertPos = 0;
3373 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3374 return QualType(AT, 0);
3375
3376 // If the atomic value type isn't canonical, this won't be a canonical type
3377 // either, so fill in the canonical type field.
3378 QualType Canonical;
3379 if (!T.isCanonical()) {
3380 Canonical = getAtomicType(getCanonicalType(T));
3381
3382 // Get the new insert position for the node we care about.
3383 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3384 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3385 }
3386 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3387 Types.push_back(New);
3388 AtomicTypes.InsertNode(New, InsertPos);
3389 return QualType(New, 0);
3390}
3391
Richard Smith02e85f32011-04-14 22:09:26 +00003392/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3393QualType ASTContext::getAutoDeductType() const {
3394 if (AutoDeductTy.isNull())
3395 AutoDeductTy = getAutoType(QualType());
3396 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3397 return AutoDeductTy;
3398}
3399
3400/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3401QualType ASTContext::getAutoRRefDeductType() const {
3402 if (AutoRRefDeductTy.isNull())
3403 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3404 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3405 return AutoRRefDeductTy;
3406}
3407
Chris Lattnerfb072462007-01-23 05:45:31 +00003408/// getTagDeclType - Return the unique reference to the type for the
3409/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003410QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003411 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003412 // FIXME: What is the design on getTagDeclType when it requires casting
3413 // away const? mutable?
3414 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003415}
3416
Mike Stump11289f42009-09-09 15:08:12 +00003417/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3418/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3419/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003420CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003421 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003422}
Chris Lattnerfb072462007-01-23 05:45:31 +00003423
Hans Wennborg27541db2011-10-27 08:29:09 +00003424/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3425CanQualType ASTContext::getIntMaxType() const {
3426 return getFromTargetType(Target->getIntMaxType());
3427}
3428
3429/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3430CanQualType ASTContext::getUIntMaxType() const {
3431 return getFromTargetType(Target->getUIntMaxType());
3432}
3433
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003434/// getSignedWCharType - Return the type of "signed wchar_t".
3435/// Used when in C++, as a GCC extension.
3436QualType ASTContext::getSignedWCharType() const {
3437 // FIXME: derive from "Target" ?
3438 return WCharTy;
3439}
3440
3441/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3442/// Used when in C++, as a GCC extension.
3443QualType ASTContext::getUnsignedWCharType() const {
3444 // FIXME: derive from "Target" ?
3445 return UnsignedIntTy;
3446}
3447
Hans Wennborg27541db2011-10-27 08:29:09 +00003448/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003449/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3450QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003451 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003452}
3453
Chris Lattnera21ad802008-04-02 05:18:44 +00003454//===----------------------------------------------------------------------===//
3455// Type Operators
3456//===----------------------------------------------------------------------===//
3457
Jay Foad39c79802011-01-12 09:06:06 +00003458CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003459 // Push qualifiers into arrays, and then discard any remaining
3460 // qualifiers.
3461 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003462 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003463 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003464 QualType Result;
3465 if (isa<ArrayType>(Ty)) {
3466 Result = getArrayDecayedType(QualType(Ty,0));
3467 } else if (isa<FunctionType>(Ty)) {
3468 Result = getPointerType(QualType(Ty, 0));
3469 } else {
3470 Result = QualType(Ty, 0);
3471 }
3472
3473 return CanQualType::CreateUnsafe(Result);
3474}
3475
John McCall6c9dd522011-01-18 07:41:22 +00003476QualType ASTContext::getUnqualifiedArrayType(QualType type,
3477 Qualifiers &quals) {
3478 SplitQualType splitType = type.getSplitUnqualifiedType();
3479
3480 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3481 // the unqualified desugared type and then drops it on the floor.
3482 // We then have to strip that sugar back off with
3483 // getUnqualifiedDesugaredType(), which is silly.
3484 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003485 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003486
3487 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003488 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003489 quals = splitType.Quals;
3490 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003491 }
3492
John McCall6c9dd522011-01-18 07:41:22 +00003493 // Otherwise, recurse on the array's element type.
3494 QualType elementType = AT->getElementType();
3495 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3496
3497 // If that didn't change the element type, AT has no qualifiers, so we
3498 // can just use the results in splitType.
3499 if (elementType == unqualElementType) {
3500 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003501 quals = splitType.Quals;
3502 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003503 }
3504
3505 // Otherwise, add in the qualifiers from the outermost type, then
3506 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003507 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003508
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003509 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003510 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003511 CAT->getSizeModifier(), 0);
3512 }
3513
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003514 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003515 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003516 }
3517
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003518 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003519 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003520 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003521 VAT->getSizeModifier(),
3522 VAT->getIndexTypeCVRQualifiers(),
3523 VAT->getBracketsRange());
3524 }
3525
3526 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003527 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003528 DSAT->getSizeModifier(), 0,
3529 SourceRange());
3530}
3531
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003532/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3533/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3534/// they point to and return true. If T1 and T2 aren't pointer types
3535/// or pointer-to-member types, or if they are not similar at this
3536/// level, returns false and leaves T1 and T2 unchanged. Top-level
3537/// qualifiers on T1 and T2 are ignored. This function will typically
3538/// be called in a loop that successively "unwraps" pointer and
3539/// pointer-to-member types to compare them at each level.
3540bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3541 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3542 *T2PtrType = T2->getAs<PointerType>();
3543 if (T1PtrType && T2PtrType) {
3544 T1 = T1PtrType->getPointeeType();
3545 T2 = T2PtrType->getPointeeType();
3546 return true;
3547 }
3548
3549 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3550 *T2MPType = T2->getAs<MemberPointerType>();
3551 if (T1MPType && T2MPType &&
3552 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3553 QualType(T2MPType->getClass(), 0))) {
3554 T1 = T1MPType->getPointeeType();
3555 T2 = T2MPType->getPointeeType();
3556 return true;
3557 }
3558
David Blaikiebbafb8a2012-03-11 07:00:24 +00003559 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003560 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3561 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3562 if (T1OPType && T2OPType) {
3563 T1 = T1OPType->getPointeeType();
3564 T2 = T2OPType->getPointeeType();
3565 return true;
3566 }
3567 }
3568
3569 // FIXME: Block pointers, too?
3570
3571 return false;
3572}
3573
Jay Foad39c79802011-01-12 09:06:06 +00003574DeclarationNameInfo
3575ASTContext::getNameForTemplate(TemplateName Name,
3576 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003577 switch (Name.getKind()) {
3578 case TemplateName::QualifiedTemplate:
3579 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003580 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003581 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3582 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003583
John McCalld9dfe3a2011-06-30 08:33:18 +00003584 case TemplateName::OverloadedTemplate: {
3585 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3586 // DNInfo work in progress: CHECKME: what about DNLoc?
3587 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3588 }
3589
3590 case TemplateName::DependentTemplate: {
3591 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003592 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003593 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003594 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3595 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003596 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003597 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3598 // DNInfo work in progress: FIXME: source locations?
3599 DeclarationNameLoc DNLoc;
3600 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3601 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3602 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003603 }
3604 }
3605
John McCalld9dfe3a2011-06-30 08:33:18 +00003606 case TemplateName::SubstTemplateTemplateParm: {
3607 SubstTemplateTemplateParmStorage *subst
3608 = Name.getAsSubstTemplateTemplateParm();
3609 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3610 NameLoc);
3611 }
3612
3613 case TemplateName::SubstTemplateTemplateParmPack: {
3614 SubstTemplateTemplateParmPackStorage *subst
3615 = Name.getAsSubstTemplateTemplateParmPack();
3616 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3617 NameLoc);
3618 }
3619 }
3620
3621 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003622}
3623
Jay Foad39c79802011-01-12 09:06:06 +00003624TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003625 switch (Name.getKind()) {
3626 case TemplateName::QualifiedTemplate:
3627 case TemplateName::Template: {
3628 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003629 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003630 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003631 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3632
3633 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003634 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003635 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003636
John McCalld9dfe3a2011-06-30 08:33:18 +00003637 case TemplateName::OverloadedTemplate:
3638 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003639
John McCalld9dfe3a2011-06-30 08:33:18 +00003640 case TemplateName::DependentTemplate: {
3641 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3642 assert(DTN && "Non-dependent template names must refer to template decls.");
3643 return DTN->CanonicalTemplateName;
3644 }
3645
3646 case TemplateName::SubstTemplateTemplateParm: {
3647 SubstTemplateTemplateParmStorage *subst
3648 = Name.getAsSubstTemplateTemplateParm();
3649 return getCanonicalTemplateName(subst->getReplacement());
3650 }
3651
3652 case TemplateName::SubstTemplateTemplateParmPack: {
3653 SubstTemplateTemplateParmPackStorage *subst
3654 = Name.getAsSubstTemplateTemplateParmPack();
3655 TemplateTemplateParmDecl *canonParameter
3656 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3657 TemplateArgument canonArgPack
3658 = getCanonicalTemplateArgument(subst->getArgumentPack());
3659 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3660 }
3661 }
3662
3663 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003664}
3665
Douglas Gregoradee3e32009-11-11 23:06:43 +00003666bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3667 X = getCanonicalTemplateName(X);
3668 Y = getCanonicalTemplateName(Y);
3669 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3670}
3671
Mike Stump11289f42009-09-09 15:08:12 +00003672TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003673ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003674 switch (Arg.getKind()) {
3675 case TemplateArgument::Null:
3676 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003677
Douglas Gregora8e02e72009-07-28 23:00:59 +00003678 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003679 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003680
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003681 case TemplateArgument::Declaration: {
3682 if (Decl *D = Arg.getAsDecl())
3683 return TemplateArgument(D->getCanonicalDecl());
3684 return TemplateArgument((Decl*)0);
3685 }
Mike Stump11289f42009-09-09 15:08:12 +00003686
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003687 case TemplateArgument::Template:
3688 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003689
3690 case TemplateArgument::TemplateExpansion:
3691 return TemplateArgument(getCanonicalTemplateName(
3692 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003693 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003694
Douglas Gregora8e02e72009-07-28 23:00:59 +00003695 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003696 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003697
Douglas Gregora8e02e72009-07-28 23:00:59 +00003698 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003699 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003700
Douglas Gregora8e02e72009-07-28 23:00:59 +00003701 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003702 if (Arg.pack_size() == 0)
3703 return Arg;
3704
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003705 TemplateArgument *CanonArgs
3706 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003707 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003708 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003709 AEnd = Arg.pack_end();
3710 A != AEnd; (void)++A, ++Idx)
3711 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003712
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003713 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003714 }
3715 }
3716
3717 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003718 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003719}
3720
Douglas Gregor333489b2009-03-27 23:10:48 +00003721NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003722ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003723 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003724 return 0;
3725
3726 switch (NNS->getKind()) {
3727 case NestedNameSpecifier::Identifier:
3728 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003729 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003730 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3731 NNS->getAsIdentifier());
3732
3733 case NestedNameSpecifier::Namespace:
3734 // A namespace is canonical; build a nested-name-specifier with
3735 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003736 return NestedNameSpecifier::Create(*this, 0,
3737 NNS->getAsNamespace()->getOriginalNamespace());
3738
3739 case NestedNameSpecifier::NamespaceAlias:
3740 // A namespace is canonical; build a nested-name-specifier with
3741 // this namespace and no prefix.
3742 return NestedNameSpecifier::Create(*this, 0,
3743 NNS->getAsNamespaceAlias()->getNamespace()
3744 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003745
3746 case NestedNameSpecifier::TypeSpec:
3747 case NestedNameSpecifier::TypeSpecWithTemplate: {
3748 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003749
3750 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3751 // break it apart into its prefix and identifier, then reconsititute those
3752 // as the canonical nested-name-specifier. This is required to canonicalize
3753 // a dependent nested-name-specifier involving typedefs of dependent-name
3754 // types, e.g.,
3755 // typedef typename T::type T1;
3756 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003757 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3758 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003759 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003760
Eli Friedman5358a0a2012-03-03 04:09:56 +00003761 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3762 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3763 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003764 return NestedNameSpecifier::Create(*this, 0, false,
3765 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003766 }
3767
3768 case NestedNameSpecifier::Global:
3769 // The global specifier is canonical and unique.
3770 return NNS;
3771 }
3772
David Blaikie8a40f702012-01-17 06:56:22 +00003773 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003774}
3775
Chris Lattner7adf0762008-08-04 07:31:14 +00003776
Jay Foad39c79802011-01-12 09:06:06 +00003777const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003778 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003779 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003780 // Handle the common positive case fast.
3781 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3782 return AT;
3783 }
Mike Stump11289f42009-09-09 15:08:12 +00003784
John McCall8ccfcb52009-09-24 19:53:00 +00003785 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003786 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003787 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003788
John McCall8ccfcb52009-09-24 19:53:00 +00003789 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003790 // implements C99 6.7.3p8: "If the specification of an array type includes
3791 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003792
Chris Lattner7adf0762008-08-04 07:31:14 +00003793 // If we get here, we either have type qualifiers on the type, or we have
3794 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003795 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003796
John McCall33ddac02011-01-19 10:06:00 +00003797 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003798 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003799
Chris Lattner7adf0762008-08-04 07:31:14 +00003800 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003801 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003802 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003803 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003804
Chris Lattner7adf0762008-08-04 07:31:14 +00003805 // Otherwise, we have an array and we have qualifiers on it. Push the
3806 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003807 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003808
Chris Lattner7adf0762008-08-04 07:31:14 +00003809 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3810 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3811 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003812 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003813 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3814 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3815 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003816 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003817
Mike Stump11289f42009-09-09 15:08:12 +00003818 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003819 = dyn_cast<DependentSizedArrayType>(ATy))
3820 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003821 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003822 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003823 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003824 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003825 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003826
Chris Lattner7adf0762008-08-04 07:31:14 +00003827 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003828 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003829 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003830 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003831 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003832 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003833}
3834
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003835QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003836 // C99 6.7.5.3p7:
3837 // A declaration of a parameter as "array of type" shall be
3838 // adjusted to "qualified pointer to type", where the type
3839 // qualifiers (if any) are those specified within the [ and ] of
3840 // the array type derivation.
3841 if (T->isArrayType())
3842 return getArrayDecayedType(T);
3843
3844 // C99 6.7.5.3p8:
3845 // A declaration of a parameter as "function returning type"
3846 // shall be adjusted to "pointer to function returning type", as
3847 // in 6.3.2.1.
3848 if (T->isFunctionType())
3849 return getPointerType(T);
3850
3851 return T;
3852}
3853
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003854QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003855 T = getVariableArrayDecayedType(T);
3856 T = getAdjustedParameterType(T);
3857 return T.getUnqualifiedType();
3858}
3859
Chris Lattnera21ad802008-04-02 05:18:44 +00003860/// getArrayDecayedType - Return the properly qualified result of decaying the
3861/// specified array type to a pointer. This operation is non-trivial when
3862/// handling typedefs etc. The canonical type of "T" must be an array type,
3863/// this returns a pointer to a properly qualified element of the array.
3864///
3865/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003866QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003867 // Get the element type with 'getAsArrayType' so that we don't lose any
3868 // typedefs in the element type of the array. This also handles propagation
3869 // of type qualifiers from the array type into the element type if present
3870 // (C99 6.7.3p8).
3871 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3872 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003873
Chris Lattner7adf0762008-08-04 07:31:14 +00003874 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003875
3876 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003877 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003878}
3879
John McCall33ddac02011-01-19 10:06:00 +00003880QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3881 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003882}
3883
John McCall33ddac02011-01-19 10:06:00 +00003884QualType ASTContext::getBaseElementType(QualType type) const {
3885 Qualifiers qs;
3886 while (true) {
3887 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003888 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003889 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003890
John McCall33ddac02011-01-19 10:06:00 +00003891 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003892 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003893 }
Mike Stump11289f42009-09-09 15:08:12 +00003894
John McCall33ddac02011-01-19 10:06:00 +00003895 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003896}
3897
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003898/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003899uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003900ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3901 uint64_t ElementCount = 1;
3902 do {
3903 ElementCount *= CA->getSize().getZExtValue();
3904 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3905 } while (CA);
3906 return ElementCount;
3907}
3908
Steve Naroff0af91202007-04-27 21:51:21 +00003909/// getFloatingRank - Return a relative rank for floating point types.
3910/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003911static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003912 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003913 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003914
John McCall9dd450b2009-09-21 23:43:11 +00003915 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3916 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003917 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003918 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003919 case BuiltinType::Float: return FloatRank;
3920 case BuiltinType::Double: return DoubleRank;
3921 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003922 }
3923}
3924
Mike Stump11289f42009-09-09 15:08:12 +00003925/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3926/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003927/// 'typeDomain' is a real floating point or complex type.
3928/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003929QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3930 QualType Domain) const {
3931 FloatingRank EltRank = getFloatingRank(Size);
3932 if (Domain->isComplexType()) {
3933 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003934 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003935 case FloatRank: return FloatComplexTy;
3936 case DoubleRank: return DoubleComplexTy;
3937 case LongDoubleRank: return LongDoubleComplexTy;
3938 }
Steve Naroff0af91202007-04-27 21:51:21 +00003939 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003940
3941 assert(Domain->isRealFloatingType() && "Unknown domain!");
3942 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003943 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003944 case FloatRank: return FloatTy;
3945 case DoubleRank: return DoubleTy;
3946 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003947 }
David Blaikief47fa302012-01-17 02:30:50 +00003948 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003949}
3950
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003951/// getFloatingTypeOrder - Compare the rank of the two specified floating
3952/// point types, ignoring the domain of the type (i.e. 'double' ==
3953/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003954/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003955int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003956 FloatingRank LHSR = getFloatingRank(LHS);
3957 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003958
Chris Lattnerb90739d2008-04-06 23:38:49 +00003959 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003960 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003961 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003962 return 1;
3963 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003964}
3965
Chris Lattner76a00cf2008-04-06 22:59:24 +00003966/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3967/// routine will assert if passed a built-in type that isn't an integer or enum,
3968/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003969unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003970 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003971
Chris Lattner76a00cf2008-04-06 22:59:24 +00003972 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003973 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003974 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003975 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003976 case BuiltinType::Char_S:
3977 case BuiltinType::Char_U:
3978 case BuiltinType::SChar:
3979 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003980 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003981 case BuiltinType::Short:
3982 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003983 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003984 case BuiltinType::Int:
3985 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003986 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003987 case BuiltinType::Long:
3988 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003989 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003990 case BuiltinType::LongLong:
3991 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003992 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003993 case BuiltinType::Int128:
3994 case BuiltinType::UInt128:
3995 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003996 }
3997}
3998
Eli Friedman629ffb92009-08-20 04:21:42 +00003999/// \brief Whether this is a promotable bitfield reference according
4000/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4001///
4002/// \returns the type this bit-field will promote to, or NULL if no
4003/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004004QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004005 if (E->isTypeDependent() || E->isValueDependent())
4006 return QualType();
4007
Eli Friedman629ffb92009-08-20 04:21:42 +00004008 FieldDecl *Field = E->getBitField();
4009 if (!Field)
4010 return QualType();
4011
4012 QualType FT = Field->getType();
4013
Richard Smithcaf33902011-10-10 18:28:20 +00004014 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004015 uint64_t IntSize = getTypeSize(IntTy);
4016 // GCC extension compatibility: if the bit-field size is less than or equal
4017 // to the size of int, it gets promoted no matter what its type is.
4018 // For instance, unsigned long bf : 4 gets promoted to signed int.
4019 if (BitWidth < IntSize)
4020 return IntTy;
4021
4022 if (BitWidth == IntSize)
4023 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4024
4025 // Types bigger than int are not subject to promotions, and therefore act
4026 // like the base type.
4027 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4028 // is ridiculous.
4029 return QualType();
4030}
4031
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004032/// getPromotedIntegerType - Returns the type that Promotable will
4033/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4034/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004035QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004036 assert(!Promotable.isNull());
4037 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004038 if (const EnumType *ET = Promotable->getAs<EnumType>())
4039 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004040
4041 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4042 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4043 // (3.9.1) can be converted to a prvalue of the first of the following
4044 // types that can represent all the values of its underlying type:
4045 // int, unsigned int, long int, unsigned long int, long long int, or
4046 // unsigned long long int [...]
4047 // FIXME: Is there some better way to compute this?
4048 if (BT->getKind() == BuiltinType::WChar_S ||
4049 BT->getKind() == BuiltinType::WChar_U ||
4050 BT->getKind() == BuiltinType::Char16 ||
4051 BT->getKind() == BuiltinType::Char32) {
4052 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4053 uint64_t FromSize = getTypeSize(BT);
4054 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4055 LongLongTy, UnsignedLongLongTy };
4056 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4057 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4058 if (FromSize < ToSize ||
4059 (FromSize == ToSize &&
4060 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4061 return PromoteTypes[Idx];
4062 }
4063 llvm_unreachable("char type should fit into long long");
4064 }
4065 }
4066
4067 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004068 if (Promotable->isSignedIntegerType())
4069 return IntTy;
4070 uint64_t PromotableSize = getTypeSize(Promotable);
4071 uint64_t IntSize = getTypeSize(IntTy);
4072 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4073 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4074}
4075
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004076/// \brief Recurses in pointer/array types until it finds an objc retainable
4077/// type and returns its ownership.
4078Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4079 while (!T.isNull()) {
4080 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4081 return T.getObjCLifetime();
4082 if (T->isArrayType())
4083 T = getBaseElementType(T);
4084 else if (const PointerType *PT = T->getAs<PointerType>())
4085 T = PT->getPointeeType();
4086 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004087 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004088 else
4089 break;
4090 }
4091
4092 return Qualifiers::OCL_None;
4093}
4094
Mike Stump11289f42009-09-09 15:08:12 +00004095/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004096/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004097/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004098int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004099 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4100 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004101 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004102
Chris Lattner76a00cf2008-04-06 22:59:24 +00004103 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4104 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004105
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004106 unsigned LHSRank = getIntegerRank(LHSC);
4107 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004108
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004109 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4110 if (LHSRank == RHSRank) return 0;
4111 return LHSRank > RHSRank ? 1 : -1;
4112 }
Mike Stump11289f42009-09-09 15:08:12 +00004113
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004114 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4115 if (LHSUnsigned) {
4116 // If the unsigned [LHS] type is larger, return it.
4117 if (LHSRank >= RHSRank)
4118 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004119
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004120 // If the signed type can represent all values of the unsigned type, it
4121 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004122 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004123 return -1;
4124 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004125
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004126 // If the unsigned [RHS] type is larger, return it.
4127 if (RHSRank >= LHSRank)
4128 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004129
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004130 // If the signed type can represent all values of the unsigned type, it
4131 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004132 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004133 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004134}
Anders Carlsson98f07902007-08-17 05:31:46 +00004135
Anders Carlsson6d417272009-11-14 21:45:58 +00004136static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004137CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4138 DeclContext *DC, IdentifierInfo *Id) {
4139 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004140 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004141 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004142 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004143 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004144}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004145
Mike Stump11289f42009-09-09 15:08:12 +00004146// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004147QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004148 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004149 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004150 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004151 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004152 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004153
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004154 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004155
Anders Carlsson98f07902007-08-17 05:31:46 +00004156 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004157 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004158 // int flags;
4159 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004160 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004161 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004162 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004163 FieldTypes[3] = LongTy;
4164
Anders Carlsson98f07902007-08-17 05:31:46 +00004165 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004166 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004167 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004168 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004169 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004170 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004171 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004172 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004173 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004174 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004175 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004176 }
4177
Douglas Gregord5058122010-02-11 01:19:42 +00004178 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004179 }
Mike Stump11289f42009-09-09 15:08:12 +00004180
Anders Carlsson98f07902007-08-17 05:31:46 +00004181 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004182}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004183
Douglas Gregor512b0772009-04-23 22:29:11 +00004184void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004185 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004186 assert(Rec && "Invalid CFConstantStringType");
4187 CFConstantStringTypeDecl = Rec->getDecl();
4188}
4189
Jay Foad39c79802011-01-12 09:06:06 +00004190QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004191 if (BlockDescriptorType)
4192 return getTagDeclType(BlockDescriptorType);
4193
4194 RecordDecl *T;
4195 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004196 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004197 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004198 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004199
4200 QualType FieldTypes[] = {
4201 UnsignedLongTy,
4202 UnsignedLongTy,
4203 };
4204
4205 const char *FieldNames[] = {
4206 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004207 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004208 };
4209
4210 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004211 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004212 SourceLocation(),
4213 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004214 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004215 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004216 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004217 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004218 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004219 T->addDecl(Field);
4220 }
4221
Douglas Gregord5058122010-02-11 01:19:42 +00004222 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004223
4224 BlockDescriptorType = T;
4225
4226 return getTagDeclType(BlockDescriptorType);
4227}
4228
Jay Foad39c79802011-01-12 09:06:06 +00004229QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004230 if (BlockDescriptorExtendedType)
4231 return getTagDeclType(BlockDescriptorExtendedType);
4232
4233 RecordDecl *T;
4234 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004235 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004236 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004237 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004238
4239 QualType FieldTypes[] = {
4240 UnsignedLongTy,
4241 UnsignedLongTy,
4242 getPointerType(VoidPtrTy),
4243 getPointerType(VoidPtrTy)
4244 };
4245
4246 const char *FieldNames[] = {
4247 "reserved",
4248 "Size",
4249 "CopyFuncPtr",
4250 "DestroyFuncPtr"
4251 };
4252
4253 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004254 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004255 SourceLocation(),
4256 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004257 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004258 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004259 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004260 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004261 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004262 T->addDecl(Field);
4263 }
4264
Douglas Gregord5058122010-02-11 01:19:42 +00004265 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004266
4267 BlockDescriptorExtendedType = T;
4268
4269 return getTagDeclType(BlockDescriptorExtendedType);
4270}
4271
Jay Foad39c79802011-01-12 09:06:06 +00004272bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004273 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004274 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004275 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004276 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4277 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004278 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004279
4280 }
4281 }
Mike Stump94967902009-10-21 18:16:27 +00004282 return false;
4283}
4284
Jay Foad39c79802011-01-12 09:06:06 +00004285QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004286ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004287 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004288 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004289 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004290 // unsigned int __flags;
4291 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004292 // void *__copy_helper; // as needed
4293 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004294 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004295 // } *
4296
Mike Stump94967902009-10-21 18:16:27 +00004297 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4298
4299 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004300 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004301 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4302 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004303 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004304 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004305 T->startDefinition();
4306 QualType Int32Ty = IntTy;
4307 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4308 QualType FieldTypes[] = {
4309 getPointerType(VoidPtrTy),
4310 getPointerType(getTagDeclType(T)),
4311 Int32Ty,
4312 Int32Ty,
4313 getPointerType(VoidPtrTy),
4314 getPointerType(VoidPtrTy),
4315 Ty
4316 };
4317
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004318 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004319 "__isa",
4320 "__forwarding",
4321 "__flags",
4322 "__size",
4323 "__copy_helper",
4324 "__destroy_helper",
4325 DeclName,
4326 };
4327
4328 for (size_t i = 0; i < 7; ++i) {
4329 if (!HasCopyAndDispose && i >=4 && i <= 5)
4330 continue;
4331 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004332 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004333 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004334 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004335 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004336 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004337 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004338 T->addDecl(Field);
4339 }
4340
Douglas Gregord5058122010-02-11 01:19:42 +00004341 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004342
4343 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004344}
4345
Douglas Gregorbab8a962011-09-08 01:46:34 +00004346TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4347 if (!ObjCInstanceTypeDecl)
4348 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4349 getTranslationUnitDecl(),
4350 SourceLocation(),
4351 SourceLocation(),
4352 &Idents.get("instancetype"),
4353 getTrivialTypeSourceInfo(getObjCIdType()));
4354 return ObjCInstanceTypeDecl;
4355}
4356
Anders Carlsson18acd442007-10-29 06:33:42 +00004357// This returns true if a type has been typedefed to BOOL:
4358// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004359static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004360 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004361 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4362 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004363
Anders Carlssond8499822007-10-29 05:01:08 +00004364 return false;
4365}
4366
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004367/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004368/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004369CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004370 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4371 return CharUnits::Zero();
4372
Ken Dyck40775002010-01-11 17:06:35 +00004373 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004374
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004375 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004376 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004377 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004378 // Treat arrays as pointers, since that's how they're passed in.
4379 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004380 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004381 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004382}
4383
4384static inline
4385std::string charUnitsToString(const CharUnits &CU) {
4386 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004387}
4388
John McCall351762c2011-02-07 10:33:21 +00004389/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004390/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004391std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4392 std::string S;
4393
David Chisnall950a9512009-11-17 19:33:30 +00004394 const BlockDecl *Decl = Expr->getBlockDecl();
4395 QualType BlockTy =
4396 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4397 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004398 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004399 // Compute size of all parameters.
4400 // Start with computing size of a pointer in number of bytes.
4401 // FIXME: There might(should) be a better way of doing this computation!
4402 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004403 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4404 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004405 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004406 E = Decl->param_end(); PI != E; ++PI) {
4407 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004408 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004409 if (sz.isZero())
4410 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004411 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004412 ParmOffset += sz;
4413 }
4414 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004415 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004416 // Block pointer and offset.
4417 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004418
4419 // Argument types.
4420 ParmOffset = PtrSize;
4421 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4422 Decl->param_end(); PI != E; ++PI) {
4423 ParmVarDecl *PVDecl = *PI;
4424 QualType PType = PVDecl->getOriginalType();
4425 if (const ArrayType *AT =
4426 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4427 // Use array's original type only if it has known number of
4428 // elements.
4429 if (!isa<ConstantArrayType>(AT))
4430 PType = PVDecl->getType();
4431 } else if (PType->isFunctionType())
4432 PType = PVDecl->getType();
4433 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004434 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004435 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004436 }
John McCall351762c2011-02-07 10:33:21 +00004437
4438 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004439}
4440
Douglas Gregora9d84932011-05-27 01:19:52 +00004441bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004442 std::string& S) {
4443 // Encode result type.
4444 getObjCEncodingForType(Decl->getResultType(), S);
4445 CharUnits ParmOffset;
4446 // Compute size of all parameters.
4447 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4448 E = Decl->param_end(); PI != E; ++PI) {
4449 QualType PType = (*PI)->getType();
4450 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004451 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004452 continue;
4453
David Chisnall50e4eba2010-12-30 14:05:53 +00004454 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004455 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004456 ParmOffset += sz;
4457 }
4458 S += charUnitsToString(ParmOffset);
4459 ParmOffset = CharUnits::Zero();
4460
4461 // Argument types.
4462 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4463 E = Decl->param_end(); PI != E; ++PI) {
4464 ParmVarDecl *PVDecl = *PI;
4465 QualType PType = PVDecl->getOriginalType();
4466 if (const ArrayType *AT =
4467 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4468 // Use array's original type only if it has known number of
4469 // elements.
4470 if (!isa<ConstantArrayType>(AT))
4471 PType = PVDecl->getType();
4472 } else if (PType->isFunctionType())
4473 PType = PVDecl->getType();
4474 getObjCEncodingForType(PType, S);
4475 S += charUnitsToString(ParmOffset);
4476 ParmOffset += getObjCEncodingTypeSize(PType);
4477 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004478
4479 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004480}
4481
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004482/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4483/// method parameter or return type. If Extended, include class names and
4484/// block object types.
4485void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4486 QualType T, std::string& S,
4487 bool Extended) const {
4488 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4489 getObjCEncodingForTypeQualifier(QT, S);
4490 // Encode parameter type.
4491 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4492 true /*OutermostType*/,
4493 false /*EncodingProperty*/,
4494 false /*StructField*/,
4495 Extended /*EncodeBlockParameters*/,
4496 Extended /*EncodeClassNames*/);
4497}
4498
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004499/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004500/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004501bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004502 std::string& S,
4503 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004504 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004505 // Encode return type.
4506 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4507 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004508 // Compute size of all parameters.
4509 // Start with computing size of a pointer in number of bytes.
4510 // FIXME: There might(should) be a better way of doing this computation!
4511 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004512 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004513 // The first two arguments (self and _cmd) are pointers; account for
4514 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004515 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004516 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004517 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004518 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004519 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004520 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004521 continue;
4522
Ken Dyck40775002010-01-11 17:06:35 +00004523 assert (sz.isPositive() &&
4524 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004525 ParmOffset += sz;
4526 }
Ken Dyck40775002010-01-11 17:06:35 +00004527 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004528 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004529 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004530
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004531 // Argument types.
4532 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004533 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004534 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004535 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004536 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004537 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004538 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4539 // Use array's original type only if it has known number of
4540 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004541 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004542 PType = PVDecl->getType();
4543 } else if (PType->isFunctionType())
4544 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004545 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4546 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004547 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004548 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004549 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004550
4551 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004552}
4553
Daniel Dunbar4932b362008-08-28 04:38:10 +00004554/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004555/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004556/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4557/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004558/// Property attributes are stored as a comma-delimited C string. The simple
4559/// attributes readonly and bycopy are encoded as single characters. The
4560/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4561/// encoded as single characters, followed by an identifier. Property types
4562/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004563/// these attributes are defined by the following enumeration:
4564/// @code
4565/// enum PropertyAttributes {
4566/// kPropertyReadOnly = 'R', // property is read-only.
4567/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4568/// kPropertyByref = '&', // property is a reference to the value last assigned
4569/// kPropertyDynamic = 'D', // property is dynamic
4570/// kPropertyGetter = 'G', // followed by getter selector name
4571/// kPropertySetter = 'S', // followed by setter selector name
4572/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004573/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004574/// kPropertyWeak = 'W' // 'weak' property
4575/// kPropertyStrong = 'P' // property GC'able
4576/// kPropertyNonAtomic = 'N' // property non-atomic
4577/// };
4578/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004579void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004580 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004581 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004582 // Collect information from the property implementation decl(s).
4583 bool Dynamic = false;
4584 ObjCPropertyImplDecl *SynthesizePID = 0;
4585
4586 // FIXME: Duplicated code due to poor abstraction.
4587 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004588 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004589 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4590 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004591 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004592 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004593 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004594 if (PID->getPropertyDecl() == PD) {
4595 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4596 Dynamic = true;
4597 } else {
4598 SynthesizePID = PID;
4599 }
4600 }
4601 }
4602 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004603 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004604 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004605 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004606 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004607 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004608 if (PID->getPropertyDecl() == PD) {
4609 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4610 Dynamic = true;
4611 } else {
4612 SynthesizePID = PID;
4613 }
4614 }
Mike Stump11289f42009-09-09 15:08:12 +00004615 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004616 }
4617 }
4618
4619 // FIXME: This is not very efficient.
4620 S = "T";
4621
4622 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004623 // GCC has some special rules regarding encoding of properties which
4624 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004625 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004626 true /* outermost type */,
4627 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004628
4629 if (PD->isReadOnly()) {
4630 S += ",R";
4631 } else {
4632 switch (PD->getSetterKind()) {
4633 case ObjCPropertyDecl::Assign: break;
4634 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004635 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004636 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004637 }
4638 }
4639
4640 // It really isn't clear at all what this means, since properties
4641 // are "dynamic by default".
4642 if (Dynamic)
4643 S += ",D";
4644
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004645 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4646 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004647
Daniel Dunbar4932b362008-08-28 04:38:10 +00004648 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4649 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004650 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004651 }
4652
4653 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4654 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004655 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004656 }
4657
4658 if (SynthesizePID) {
4659 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4660 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004661 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004662 }
4663
4664 // FIXME: OBJCGC: weak & strong
4665}
4666
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004667/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004668/// Another legacy compatibility encoding: 32-bit longs are encoded as
4669/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004670/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4671///
4672void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004673 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004674 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004675 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004676 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004677 else
Jay Foad39c79802011-01-12 09:06:06 +00004678 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004679 PointeeTy = IntTy;
4680 }
4681 }
4682}
4683
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004684void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004685 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004686 // We follow the behavior of gcc, expanding structures which are
4687 // directly pointed to, and expanding embedded structures. Note that
4688 // these rules are sufficient to prevent recursive encoding of the
4689 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004690 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004691 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004692}
4693
David Chisnallb190a2c2010-06-04 01:10:52 +00004694static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4695 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004696 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004697 case BuiltinType::Void: return 'v';
4698 case BuiltinType::Bool: return 'B';
4699 case BuiltinType::Char_U:
4700 case BuiltinType::UChar: return 'C';
4701 case BuiltinType::UShort: return 'S';
4702 case BuiltinType::UInt: return 'I';
4703 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004704 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004705 case BuiltinType::UInt128: return 'T';
4706 case BuiltinType::ULongLong: return 'Q';
4707 case BuiltinType::Char_S:
4708 case BuiltinType::SChar: return 'c';
4709 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004710 case BuiltinType::WChar_S:
4711 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004712 case BuiltinType::Int: return 'i';
4713 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004714 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004715 case BuiltinType::LongLong: return 'q';
4716 case BuiltinType::Int128: return 't';
4717 case BuiltinType::Float: return 'f';
4718 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004719 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004720 }
4721}
4722
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004723static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4724 EnumDecl *Enum = ET->getDecl();
4725
4726 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4727 if (!Enum->isFixed())
4728 return 'i';
4729
4730 // The encoding of a fixed enum type matches its fixed underlying type.
4731 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4732}
4733
Jay Foad39c79802011-01-12 09:06:06 +00004734static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004735 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004736 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004737 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004738 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4739 // The GNU runtime requires more information; bitfields are encoded as b,
4740 // then the offset (in bits) of the first element, then the type of the
4741 // bitfield, then the size in bits. For example, in this structure:
4742 //
4743 // struct
4744 // {
4745 // int integer;
4746 // int flags:2;
4747 // };
4748 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4749 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4750 // information is not especially sensible, but we're stuck with it for
4751 // compatibility with GCC, although providing it breaks anything that
4752 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004753 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004754 const RecordDecl *RD = FD->getParent();
4755 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004756 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004757 if (const EnumType *ET = T->getAs<EnumType>())
4758 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004759 else
Jay Foad39c79802011-01-12 09:06:06 +00004760 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004761 }
Richard Smithcaf33902011-10-10 18:28:20 +00004762 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004763}
4764
Daniel Dunbar07d07852009-10-18 21:17:35 +00004765// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004766void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4767 bool ExpandPointedToStructures,
4768 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004769 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004770 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004771 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004772 bool StructField,
4773 bool EncodeBlockParameters,
4774 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004775 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004776 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004777 return EncodeBitField(this, S, T, FD);
4778 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004779 return;
4780 }
Mike Stump11289f42009-09-09 15:08:12 +00004781
John McCall9dd450b2009-09-21 23:43:11 +00004782 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004783 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004784 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004785 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004786 return;
4787 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004788
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004789 // encoding for pointer or r3eference types.
4790 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004791 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004792 if (PT->isObjCSelType()) {
4793 S += ':';
4794 return;
4795 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004796 PointeeTy = PT->getPointeeType();
4797 }
4798 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4799 PointeeTy = RT->getPointeeType();
4800 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004801 bool isReadOnly = false;
4802 // For historical/compatibility reasons, the read-only qualifier of the
4803 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4804 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004805 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004806 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004807 if (OutermostType && T.isConstQualified()) {
4808 isReadOnly = true;
4809 S += 'r';
4810 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004811 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004812 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004813 while (P->getAs<PointerType>())
4814 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004815 if (P.isConstQualified()) {
4816 isReadOnly = true;
4817 S += 'r';
4818 }
4819 }
4820 if (isReadOnly) {
4821 // Another legacy compatibility encoding. Some ObjC qualifier and type
4822 // combinations need to be rearranged.
4823 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004824 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004825 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004826 }
Mike Stump11289f42009-09-09 15:08:12 +00004827
Anders Carlssond8499822007-10-29 05:01:08 +00004828 if (PointeeTy->isCharType()) {
4829 // char pointer types should be encoded as '*' unless it is a
4830 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004831 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004832 S += '*';
4833 return;
4834 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004835 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004836 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4837 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4838 S += '#';
4839 return;
4840 }
4841 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4842 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4843 S += '@';
4844 return;
4845 }
4846 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004847 }
Anders Carlssond8499822007-10-29 05:01:08 +00004848 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004849 getLegacyIntegralTypeEncoding(PointeeTy);
4850
Mike Stump11289f42009-09-09 15:08:12 +00004851 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004852 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004853 return;
4854 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004855
Chris Lattnere7cabb92009-07-13 00:10:46 +00004856 if (const ArrayType *AT =
4857 // Ignore type qualifiers etc.
4858 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004859 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004860 // Incomplete arrays are encoded as a pointer to the array element.
4861 S += '^';
4862
Mike Stump11289f42009-09-09 15:08:12 +00004863 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004864 false, ExpandStructures, FD);
4865 } else {
4866 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004867
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004868 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4869 if (getTypeSize(CAT->getElementType()) == 0)
4870 S += '0';
4871 else
4872 S += llvm::utostr(CAT->getSize().getZExtValue());
4873 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004874 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004875 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4876 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004877 S += '0';
4878 }
Mike Stump11289f42009-09-09 15:08:12 +00004879
4880 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004881 false, ExpandStructures, FD);
4882 S += ']';
4883 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004884 return;
4885 }
Mike Stump11289f42009-09-09 15:08:12 +00004886
John McCall9dd450b2009-09-21 23:43:11 +00004887 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004888 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004889 return;
4890 }
Mike Stump11289f42009-09-09 15:08:12 +00004891
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004892 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004893 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004894 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004895 // Anonymous structures print as '?'
4896 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4897 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004898 if (ClassTemplateSpecializationDecl *Spec
4899 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4900 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4901 std::string TemplateArgsStr
4902 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004903 TemplateArgs.data(),
4904 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004905 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004906
4907 S += TemplateArgsStr;
4908 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004909 } else {
4910 S += '?';
4911 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004912 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004913 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004914 if (!RDecl->isUnion()) {
4915 getObjCEncodingForStructureImpl(RDecl, S, FD);
4916 } else {
4917 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4918 FieldEnd = RDecl->field_end();
4919 Field != FieldEnd; ++Field) {
4920 if (FD) {
4921 S += '"';
4922 S += Field->getNameAsString();
4923 S += '"';
4924 }
Mike Stump11289f42009-09-09 15:08:12 +00004925
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004926 // Special case bit-fields.
4927 if (Field->isBitField()) {
4928 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004929 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004930 } else {
4931 QualType qt = Field->getType();
4932 getLegacyIntegralTypeEncoding(qt);
4933 getObjCEncodingForTypeImpl(qt, S, false, true,
4934 FD, /*OutermostType*/false,
4935 /*EncodingProperty*/false,
4936 /*StructField*/true);
4937 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004938 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004939 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004940 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004941 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004942 return;
4943 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004944
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004945 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004946 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004947 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004948 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004949 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004950 return;
4951 }
Mike Stump11289f42009-09-09 15:08:12 +00004952
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004953 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004954 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004955 if (EncodeBlockParameters) {
4956 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4957
4958 S += '<';
4959 // Block return type
4960 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4961 ExpandPointedToStructures, ExpandStructures,
4962 FD,
4963 false /* OutermostType */,
4964 EncodingProperty,
4965 false /* StructField */,
4966 EncodeBlockParameters,
4967 EncodeClassNames);
4968 // Block self
4969 S += "@?";
4970 // Block parameters
4971 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4972 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4973 E = FPT->arg_type_end(); I && (I != E); ++I) {
4974 getObjCEncodingForTypeImpl(*I, S,
4975 ExpandPointedToStructures,
4976 ExpandStructures,
4977 FD,
4978 false /* OutermostType */,
4979 EncodingProperty,
4980 false /* StructField */,
4981 EncodeBlockParameters,
4982 EncodeClassNames);
4983 }
4984 }
4985 S += '>';
4986 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004987 return;
4988 }
Mike Stump11289f42009-09-09 15:08:12 +00004989
John McCall8b07ec22010-05-15 11:32:37 +00004990 // Ignore protocol qualifiers when mangling at this level.
4991 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4992 T = OT->getBaseType();
4993
John McCall8ccfcb52009-09-24 19:53:00 +00004994 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004995 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004996 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004997 S += '{';
4998 const IdentifierInfo *II = OI->getIdentifier();
4999 S += II->getName();
5000 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005001 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005002 DeepCollectObjCIvars(OI, true, Ivars);
5003 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005004 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005005 if (Field->isBitField())
5006 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005007 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005008 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005009 }
5010 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005011 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005012 }
Mike Stump11289f42009-09-09 15:08:12 +00005013
John McCall9dd450b2009-09-21 23:43:11 +00005014 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005015 if (OPT->isObjCIdType()) {
5016 S += '@';
5017 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005018 }
Mike Stump11289f42009-09-09 15:08:12 +00005019
Steve Narofff0c86112009-10-28 22:03:49 +00005020 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5021 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5022 // Since this is a binary compatibility issue, need to consult with runtime
5023 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005024 S += '#';
5025 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005026 }
Mike Stump11289f42009-09-09 15:08:12 +00005027
Chris Lattnere7cabb92009-07-13 00:10:46 +00005028 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005029 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005030 ExpandPointedToStructures,
5031 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005032 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005033 // Note that we do extended encoding of protocol qualifer list
5034 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005035 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005036 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5037 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005038 S += '<';
5039 S += (*I)->getNameAsString();
5040 S += '>';
5041 }
5042 S += '"';
5043 }
5044 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005045 }
Mike Stump11289f42009-09-09 15:08:12 +00005046
Chris Lattnere7cabb92009-07-13 00:10:46 +00005047 QualType PointeeTy = OPT->getPointeeType();
5048 if (!EncodingProperty &&
5049 isa<TypedefType>(PointeeTy.getTypePtr())) {
5050 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005051 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005052 // {...};
5053 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005054 getObjCEncodingForTypeImpl(PointeeTy, S,
5055 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005056 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005057 return;
5058 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005059
5060 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005061 if (OPT->getInterfaceDecl() &&
5062 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005063 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005064 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005065 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5066 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005067 S += '<';
5068 S += (*I)->getNameAsString();
5069 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005070 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005071 S += '"';
5072 }
5073 return;
5074 }
Mike Stump11289f42009-09-09 15:08:12 +00005075
John McCalla9e6e8d2010-05-17 23:56:34 +00005076 // gcc just blithely ignores member pointers.
5077 // TODO: maybe there should be a mangling for these
5078 if (T->getAs<MemberPointerType>())
5079 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005080
5081 if (T->isVectorType()) {
5082 // This matches gcc's encoding, even though technically it is
5083 // insufficient.
5084 // FIXME. We should do a better job than gcc.
5085 return;
5086 }
5087
David Blaikie83d382b2011-09-23 05:06:16 +00005088 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005089}
5090
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005091void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5092 std::string &S,
5093 const FieldDecl *FD,
5094 bool includeVBases) const {
5095 assert(RDecl && "Expected non-null RecordDecl");
5096 assert(!RDecl->isUnion() && "Should not be called for unions");
5097 if (!RDecl->getDefinition())
5098 return;
5099
5100 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5101 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5102 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5103
5104 if (CXXRec) {
5105 for (CXXRecordDecl::base_class_iterator
5106 BI = CXXRec->bases_begin(),
5107 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5108 if (!BI->isVirtual()) {
5109 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005110 if (base->isEmpty())
5111 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005112 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005113 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5114 std::make_pair(offs, base));
5115 }
5116 }
5117 }
5118
5119 unsigned i = 0;
5120 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5121 FieldEnd = RDecl->field_end();
5122 Field != FieldEnd; ++Field, ++i) {
5123 uint64_t offs = layout.getFieldOffset(i);
5124 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005125 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005126 }
5127
5128 if (CXXRec && includeVBases) {
5129 for (CXXRecordDecl::base_class_iterator
5130 BI = CXXRec->vbases_begin(),
5131 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5132 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005133 if (base->isEmpty())
5134 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005135 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005136 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5137 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5138 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005139 }
5140 }
5141
5142 CharUnits size;
5143 if (CXXRec) {
5144 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5145 } else {
5146 size = layout.getSize();
5147 }
5148
5149 uint64_t CurOffs = 0;
5150 std::multimap<uint64_t, NamedDecl *>::iterator
5151 CurLayObj = FieldOrBaseOffsets.begin();
5152
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005153 if (CXXRec && CXXRec->isDynamicClass() &&
5154 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005155 if (FD) {
5156 S += "\"_vptr$";
5157 std::string recname = CXXRec->getNameAsString();
5158 if (recname.empty()) recname = "?";
5159 S += recname;
5160 S += '"';
5161 }
5162 S += "^^?";
5163 CurOffs += getTypeSize(VoidPtrTy);
5164 }
5165
5166 if (!RDecl->hasFlexibleArrayMember()) {
5167 // Mark the end of the structure.
5168 uint64_t offs = toBits(size);
5169 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5170 std::make_pair(offs, (NamedDecl*)0));
5171 }
5172
5173 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5174 assert(CurOffs <= CurLayObj->first);
5175
5176 if (CurOffs < CurLayObj->first) {
5177 uint64_t padding = CurLayObj->first - CurOffs;
5178 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5179 // packing/alignment of members is different that normal, in which case
5180 // the encoding will be out-of-sync with the real layout.
5181 // If the runtime switches to just consider the size of types without
5182 // taking into account alignment, we could make padding explicit in the
5183 // encoding (e.g. using arrays of chars). The encoding strings would be
5184 // longer then though.
5185 CurOffs += padding;
5186 }
5187
5188 NamedDecl *dcl = CurLayObj->second;
5189 if (dcl == 0)
5190 break; // reached end of structure.
5191
5192 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5193 // We expand the bases without their virtual bases since those are going
5194 // in the initial structure. Note that this differs from gcc which
5195 // expands virtual bases each time one is encountered in the hierarchy,
5196 // making the encoding type bigger than it really is.
5197 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005198 assert(!base->isEmpty());
5199 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005200 } else {
5201 FieldDecl *field = cast<FieldDecl>(dcl);
5202 if (FD) {
5203 S += '"';
5204 S += field->getNameAsString();
5205 S += '"';
5206 }
5207
5208 if (field->isBitField()) {
5209 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005210 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005211 } else {
5212 QualType qt = field->getType();
5213 getLegacyIntegralTypeEncoding(qt);
5214 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5215 /*OutermostType*/false,
5216 /*EncodingProperty*/false,
5217 /*StructField*/true);
5218 CurOffs += getTypeSize(field->getType());
5219 }
5220 }
5221 }
5222}
5223
Mike Stump11289f42009-09-09 15:08:12 +00005224void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005225 std::string& S) const {
5226 if (QT & Decl::OBJC_TQ_In)
5227 S += 'n';
5228 if (QT & Decl::OBJC_TQ_Inout)
5229 S += 'N';
5230 if (QT & Decl::OBJC_TQ_Out)
5231 S += 'o';
5232 if (QT & Decl::OBJC_TQ_Bycopy)
5233 S += 'O';
5234 if (QT & Decl::OBJC_TQ_Byref)
5235 S += 'R';
5236 if (QT & Decl::OBJC_TQ_Oneway)
5237 S += 'V';
5238}
5239
Douglas Gregor3ea72692011-08-12 05:46:01 +00005240TypedefDecl *ASTContext::getObjCIdDecl() const {
5241 if (!ObjCIdDecl) {
5242 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5243 T = getObjCObjectPointerType(T);
5244 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5245 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5246 getTranslationUnitDecl(),
5247 SourceLocation(), SourceLocation(),
5248 &Idents.get("id"), IdInfo);
5249 }
5250
5251 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005252}
5253
Douglas Gregor52e02802011-08-12 06:17:30 +00005254TypedefDecl *ASTContext::getObjCSelDecl() const {
5255 if (!ObjCSelDecl) {
5256 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5257 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5258 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5259 getTranslationUnitDecl(),
5260 SourceLocation(), SourceLocation(),
5261 &Idents.get("SEL"), SelInfo);
5262 }
5263 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005264}
5265
Douglas Gregor0a586182011-08-12 05:59:41 +00005266TypedefDecl *ASTContext::getObjCClassDecl() const {
5267 if (!ObjCClassDecl) {
5268 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5269 T = getObjCObjectPointerType(T);
5270 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5271 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5272 getTranslationUnitDecl(),
5273 SourceLocation(), SourceLocation(),
5274 &Idents.get("Class"), ClassInfo);
5275 }
5276
5277 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005278}
5279
Douglas Gregord53ae832012-01-17 18:09:05 +00005280ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5281 if (!ObjCProtocolClassDecl) {
5282 ObjCProtocolClassDecl
5283 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5284 SourceLocation(),
5285 &Idents.get("Protocol"),
5286 /*PrevDecl=*/0,
5287 SourceLocation(), true);
5288 }
5289
5290 return ObjCProtocolClassDecl;
5291}
5292
Meador Inge5d3fb222012-06-16 03:34:49 +00005293//===----------------------------------------------------------------------===//
5294// __builtin_va_list Construction Functions
5295//===----------------------------------------------------------------------===//
5296
5297static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5298 // typedef char* __builtin_va_list;
5299 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5300 TypeSourceInfo *TInfo
5301 = Context->getTrivialTypeSourceInfo(CharPtrType);
5302
5303 TypedefDecl *VaListTypeDecl
5304 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5305 Context->getTranslationUnitDecl(),
5306 SourceLocation(), SourceLocation(),
5307 &Context->Idents.get("__builtin_va_list"),
5308 TInfo);
5309 return VaListTypeDecl;
5310}
5311
5312static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5313 // typedef void* __builtin_va_list;
5314 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5315 TypeSourceInfo *TInfo
5316 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5317
5318 TypedefDecl *VaListTypeDecl
5319 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5320 Context->getTranslationUnitDecl(),
5321 SourceLocation(), SourceLocation(),
5322 &Context->Idents.get("__builtin_va_list"),
5323 TInfo);
5324 return VaListTypeDecl;
5325}
5326
5327static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5328 // typedef struct __va_list_tag {
5329 RecordDecl *VaListTagDecl;
5330
5331 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5332 Context->getTranslationUnitDecl(),
5333 &Context->Idents.get("__va_list_tag"));
5334 VaListTagDecl->startDefinition();
5335
5336 const size_t NumFields = 5;
5337 QualType FieldTypes[NumFields];
5338 const char *FieldNames[NumFields];
5339
5340 // unsigned char gpr;
5341 FieldTypes[0] = Context->UnsignedCharTy;
5342 FieldNames[0] = "gpr";
5343
5344 // unsigned char fpr;
5345 FieldTypes[1] = Context->UnsignedCharTy;
5346 FieldNames[1] = "fpr";
5347
5348 // unsigned short reserved;
5349 FieldTypes[2] = Context->UnsignedShortTy;
5350 FieldNames[2] = "reserved";
5351
5352 // void* overflow_arg_area;
5353 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5354 FieldNames[3] = "overflow_arg_area";
5355
5356 // void* reg_save_area;
5357 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5358 FieldNames[4] = "reg_save_area";
5359
5360 // Create fields
5361 for (unsigned i = 0; i < NumFields; ++i) {
5362 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5363 SourceLocation(),
5364 SourceLocation(),
5365 &Context->Idents.get(FieldNames[i]),
5366 FieldTypes[i], /*TInfo=*/0,
5367 /*BitWidth=*/0,
5368 /*Mutable=*/false,
5369 ICIS_NoInit);
5370 Field->setAccess(AS_public);
5371 VaListTagDecl->addDecl(Field);
5372 }
5373 VaListTagDecl->completeDefinition();
5374 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005375 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005376
5377 // } __va_list_tag;
5378 TypedefDecl *VaListTagTypedefDecl
5379 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5380 Context->getTranslationUnitDecl(),
5381 SourceLocation(), SourceLocation(),
5382 &Context->Idents.get("__va_list_tag"),
5383 Context->getTrivialTypeSourceInfo(VaListTagType));
5384 QualType VaListTagTypedefType =
5385 Context->getTypedefType(VaListTagTypedefDecl);
5386
5387 // typedef __va_list_tag __builtin_va_list[1];
5388 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5389 QualType VaListTagArrayType
5390 = Context->getConstantArrayType(VaListTagTypedefType,
5391 Size, ArrayType::Normal, 0);
5392 TypeSourceInfo *TInfo
5393 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5394 TypedefDecl *VaListTypedefDecl
5395 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5396 Context->getTranslationUnitDecl(),
5397 SourceLocation(), SourceLocation(),
5398 &Context->Idents.get("__builtin_va_list"),
5399 TInfo);
5400
5401 return VaListTypedefDecl;
5402}
5403
5404static TypedefDecl *
5405CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5406 // typedef struct __va_list_tag {
5407 RecordDecl *VaListTagDecl;
5408 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5409 Context->getTranslationUnitDecl(),
5410 &Context->Idents.get("__va_list_tag"));
5411 VaListTagDecl->startDefinition();
5412
5413 const size_t NumFields = 4;
5414 QualType FieldTypes[NumFields];
5415 const char *FieldNames[NumFields];
5416
5417 // unsigned gp_offset;
5418 FieldTypes[0] = Context->UnsignedIntTy;
5419 FieldNames[0] = "gp_offset";
5420
5421 // unsigned fp_offset;
5422 FieldTypes[1] = Context->UnsignedIntTy;
5423 FieldNames[1] = "fp_offset";
5424
5425 // void* overflow_arg_area;
5426 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5427 FieldNames[2] = "overflow_arg_area";
5428
5429 // void* reg_save_area;
5430 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5431 FieldNames[3] = "reg_save_area";
5432
5433 // Create fields
5434 for (unsigned i = 0; i < NumFields; ++i) {
5435 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5436 VaListTagDecl,
5437 SourceLocation(),
5438 SourceLocation(),
5439 &Context->Idents.get(FieldNames[i]),
5440 FieldTypes[i], /*TInfo=*/0,
5441 /*BitWidth=*/0,
5442 /*Mutable=*/false,
5443 ICIS_NoInit);
5444 Field->setAccess(AS_public);
5445 VaListTagDecl->addDecl(Field);
5446 }
5447 VaListTagDecl->completeDefinition();
5448 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005449 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005450
5451 // } __va_list_tag;
5452 TypedefDecl *VaListTagTypedefDecl
5453 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5454 Context->getTranslationUnitDecl(),
5455 SourceLocation(), SourceLocation(),
5456 &Context->Idents.get("__va_list_tag"),
5457 Context->getTrivialTypeSourceInfo(VaListTagType));
5458 QualType VaListTagTypedefType =
5459 Context->getTypedefType(VaListTagTypedefDecl);
5460
5461 // typedef __va_list_tag __builtin_va_list[1];
5462 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5463 QualType VaListTagArrayType
5464 = Context->getConstantArrayType(VaListTagTypedefType,
5465 Size, ArrayType::Normal,0);
5466 TypeSourceInfo *TInfo
5467 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5468 TypedefDecl *VaListTypedefDecl
5469 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5470 Context->getTranslationUnitDecl(),
5471 SourceLocation(), SourceLocation(),
5472 &Context->Idents.get("__builtin_va_list"),
5473 TInfo);
5474
5475 return VaListTypedefDecl;
5476}
5477
5478static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5479 // typedef int __builtin_va_list[4];
5480 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5481 QualType IntArrayType
5482 = Context->getConstantArrayType(Context->IntTy,
5483 Size, ArrayType::Normal, 0);
5484 TypedefDecl *VaListTypedefDecl
5485 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5486 Context->getTranslationUnitDecl(),
5487 SourceLocation(), SourceLocation(),
5488 &Context->Idents.get("__builtin_va_list"),
5489 Context->getTrivialTypeSourceInfo(IntArrayType));
5490
5491 return VaListTypedefDecl;
5492}
5493
5494static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5495 TargetInfo::BuiltinVaListKind Kind) {
5496 switch (Kind) {
5497 case TargetInfo::CharPtrBuiltinVaList:
5498 return CreateCharPtrBuiltinVaListDecl(Context);
5499 case TargetInfo::VoidPtrBuiltinVaList:
5500 return CreateVoidPtrBuiltinVaListDecl(Context);
5501 case TargetInfo::PowerABIBuiltinVaList:
5502 return CreatePowerABIBuiltinVaListDecl(Context);
5503 case TargetInfo::X86_64ABIBuiltinVaList:
5504 return CreateX86_64ABIBuiltinVaListDecl(Context);
5505 case TargetInfo::PNaClABIBuiltinVaList:
5506 return CreatePNaClABIBuiltinVaListDecl(Context);
5507 }
5508
5509 llvm_unreachable("Unhandled __builtin_va_list type kind");
5510}
5511
5512TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5513 if (!BuiltinVaListDecl)
5514 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5515
5516 return BuiltinVaListDecl;
5517}
5518
Meador Ingecfb60902012-07-01 15:57:25 +00005519QualType ASTContext::getVaListTagType() const {
5520 // Force the creation of VaListTagTy by building the __builtin_va_list
5521 // declaration.
5522 if (VaListTagTy.isNull())
5523 (void) getBuiltinVaListDecl();
5524
5525 return VaListTagTy;
5526}
5527
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005528void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005529 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005530 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005531
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005532 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005533}
5534
John McCalld28ae272009-12-02 08:04:21 +00005535/// \brief Retrieve the template name that corresponds to a non-empty
5536/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005537TemplateName
5538ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5539 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005540 unsigned size = End - Begin;
5541 assert(size > 1 && "set is not overloaded!");
5542
5543 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5544 size * sizeof(FunctionTemplateDecl*));
5545 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5546
5547 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005548 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005549 NamedDecl *D = *I;
5550 assert(isa<FunctionTemplateDecl>(D) ||
5551 (isa<UsingShadowDecl>(D) &&
5552 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5553 *Storage++ = D;
5554 }
5555
5556 return TemplateName(OT);
5557}
5558
Douglas Gregordc572a32009-03-30 22:58:21 +00005559/// \brief Retrieve the template name that represents a qualified
5560/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005561TemplateName
5562ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5563 bool TemplateKeyword,
5564 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005565 assert(NNS && "Missing nested-name-specifier in qualified template name");
5566
Douglas Gregorc42075a2010-02-04 18:10:26 +00005567 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005568 llvm::FoldingSetNodeID ID;
5569 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5570
5571 void *InsertPos = 0;
5572 QualifiedTemplateName *QTN =
5573 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5574 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005575 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5576 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005577 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5578 }
5579
5580 return TemplateName(QTN);
5581}
5582
5583/// \brief Retrieve the template name that represents a dependent
5584/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005585TemplateName
5586ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5587 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005588 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005589 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005590
5591 llvm::FoldingSetNodeID ID;
5592 DependentTemplateName::Profile(ID, NNS, Name);
5593
5594 void *InsertPos = 0;
5595 DependentTemplateName *QTN =
5596 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5597
5598 if (QTN)
5599 return TemplateName(QTN);
5600
5601 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5602 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005603 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5604 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005605 } else {
5606 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005607 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5608 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005609 DependentTemplateName *CheckQTN =
5610 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5611 assert(!CheckQTN && "Dependent type name canonicalization broken");
5612 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005613 }
5614
5615 DependentTemplateNames.InsertNode(QTN, InsertPos);
5616 return TemplateName(QTN);
5617}
5618
Douglas Gregor71395fa2009-11-04 00:56:37 +00005619/// \brief Retrieve the template name that represents a dependent
5620/// template name such as \c MetaFun::template operator+.
5621TemplateName
5622ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005623 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005624 assert((!NNS || NNS->isDependent()) &&
5625 "Nested name specifier must be dependent");
5626
5627 llvm::FoldingSetNodeID ID;
5628 DependentTemplateName::Profile(ID, NNS, Operator);
5629
5630 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005631 DependentTemplateName *QTN
5632 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005633
5634 if (QTN)
5635 return TemplateName(QTN);
5636
5637 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5638 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005639 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5640 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005641 } else {
5642 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005643 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5644 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005645
5646 DependentTemplateName *CheckQTN
5647 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5648 assert(!CheckQTN && "Dependent template name canonicalization broken");
5649 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005650 }
5651
5652 DependentTemplateNames.InsertNode(QTN, InsertPos);
5653 return TemplateName(QTN);
5654}
5655
Douglas Gregor5590be02011-01-15 06:45:20 +00005656TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005657ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5658 TemplateName replacement) const {
5659 llvm::FoldingSetNodeID ID;
5660 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5661
5662 void *insertPos = 0;
5663 SubstTemplateTemplateParmStorage *subst
5664 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5665
5666 if (!subst) {
5667 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5668 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5669 }
5670
5671 return TemplateName(subst);
5672}
5673
5674TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005675ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5676 const TemplateArgument &ArgPack) const {
5677 ASTContext &Self = const_cast<ASTContext &>(*this);
5678 llvm::FoldingSetNodeID ID;
5679 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5680
5681 void *InsertPos = 0;
5682 SubstTemplateTemplateParmPackStorage *Subst
5683 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5684
5685 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005686 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005687 ArgPack.pack_size(),
5688 ArgPack.pack_begin());
5689 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5690 }
5691
5692 return TemplateName(Subst);
5693}
5694
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005695/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005696/// TargetInfo, produce the corresponding type. The unsigned @p Type
5697/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005698CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005699 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005700 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005701 case TargetInfo::SignedShort: return ShortTy;
5702 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5703 case TargetInfo::SignedInt: return IntTy;
5704 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5705 case TargetInfo::SignedLong: return LongTy;
5706 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5707 case TargetInfo::SignedLongLong: return LongLongTy;
5708 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5709 }
5710
David Blaikie83d382b2011-09-23 05:06:16 +00005711 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005712}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005713
5714//===----------------------------------------------------------------------===//
5715// Type Predicates.
5716//===----------------------------------------------------------------------===//
5717
Fariborz Jahanian96207692009-02-18 21:49:28 +00005718/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5719/// garbage collection attribute.
5720///
John McCall553d45a2011-01-12 00:34:59 +00005721Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005722 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005723 return Qualifiers::GCNone;
5724
David Blaikiebbafb8a2012-03-11 07:00:24 +00005725 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005726 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5727
5728 // Default behaviour under objective-C's gc is for ObjC pointers
5729 // (or pointers to them) be treated as though they were declared
5730 // as __strong.
5731 if (GCAttrs == Qualifiers::GCNone) {
5732 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5733 return Qualifiers::Strong;
5734 else if (Ty->isPointerType())
5735 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5736 } else {
5737 // It's not valid to set GC attributes on anything that isn't a
5738 // pointer.
5739#ifndef NDEBUG
5740 QualType CT = Ty->getCanonicalTypeInternal();
5741 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5742 CT = AT->getElementType();
5743 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5744#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005745 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005746 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005747}
5748
Chris Lattner49af6a42008-04-07 06:51:04 +00005749//===----------------------------------------------------------------------===//
5750// Type Compatibility Testing
5751//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005752
Mike Stump11289f42009-09-09 15:08:12 +00005753/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005754/// compatible.
5755static bool areCompatVectorTypes(const VectorType *LHS,
5756 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005757 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005758 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005759 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005760}
5761
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005762bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5763 QualType SecondVec) {
5764 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5765 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5766
5767 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5768 return true;
5769
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005770 // Treat Neon vector types and most AltiVec vector types as if they are the
5771 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005772 const VectorType *First = FirstVec->getAs<VectorType>();
5773 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005774 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005775 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005776 First->getVectorKind() != VectorType::AltiVecPixel &&
5777 First->getVectorKind() != VectorType::AltiVecBool &&
5778 Second->getVectorKind() != VectorType::AltiVecPixel &&
5779 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005780 return true;
5781
5782 return false;
5783}
5784
Steve Naroff8e6aee52009-07-23 01:01:38 +00005785//===----------------------------------------------------------------------===//
5786// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5787//===----------------------------------------------------------------------===//
5788
5789/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5790/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005791bool
5792ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5793 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005794 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005795 return true;
5796 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5797 E = rProto->protocol_end(); PI != E; ++PI)
5798 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5799 return true;
5800 return false;
5801}
5802
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005803/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00005804/// return true if lhs's protocols conform to rhs's protocol; false
5805/// otherwise.
5806bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5807 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5808 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5809 return false;
5810}
5811
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005812/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5813/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005814bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5815 QualType rhs) {
5816 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5817 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5818 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5819
5820 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5821 E = lhsQID->qual_end(); I != E; ++I) {
5822 bool match = false;
5823 ObjCProtocolDecl *lhsProto = *I;
5824 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5825 E = rhsOPT->qual_end(); J != E; ++J) {
5826 ObjCProtocolDecl *rhsProto = *J;
5827 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5828 match = true;
5829 break;
5830 }
5831 }
5832 if (!match)
5833 return false;
5834 }
5835 return true;
5836}
5837
Steve Naroff8e6aee52009-07-23 01:01:38 +00005838/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5839/// ObjCQualifiedIDType.
5840bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5841 bool compare) {
5842 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005843 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005844 lhs->isObjCIdType() || lhs->isObjCClassType())
5845 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005846 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005847 rhs->isObjCIdType() || rhs->isObjCClassType())
5848 return true;
5849
5850 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005851 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005852
Steve Naroff8e6aee52009-07-23 01:01:38 +00005853 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005854
Steve Naroff8e6aee52009-07-23 01:01:38 +00005855 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005856 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005857 // make sure we check the class hierarchy.
5858 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5859 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5860 E = lhsQID->qual_end(); I != E; ++I) {
5861 // when comparing an id<P> on lhs with a static type on rhs,
5862 // see if static class implements all of id's protocols, directly or
5863 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005864 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005865 return false;
5866 }
5867 }
5868 // If there are no qualifiers and no interface, we have an 'id'.
5869 return true;
5870 }
Mike Stump11289f42009-09-09 15:08:12 +00005871 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005872 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5873 E = lhsQID->qual_end(); I != E; ++I) {
5874 ObjCProtocolDecl *lhsProto = *I;
5875 bool match = false;
5876
5877 // when comparing an id<P> on lhs with a static type on rhs,
5878 // see if static class implements all of id's protocols, directly or
5879 // through its super class and categories.
5880 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5881 E = rhsOPT->qual_end(); J != E; ++J) {
5882 ObjCProtocolDecl *rhsProto = *J;
5883 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5884 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5885 match = true;
5886 break;
5887 }
5888 }
Mike Stump11289f42009-09-09 15:08:12 +00005889 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005890 // make sure we check the class hierarchy.
5891 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5892 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5893 E = lhsQID->qual_end(); I != E; ++I) {
5894 // when comparing an id<P> on lhs with a static type on rhs,
5895 // see if static class implements all of id's protocols, directly or
5896 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005897 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005898 match = true;
5899 break;
5900 }
5901 }
5902 }
5903 if (!match)
5904 return false;
5905 }
Mike Stump11289f42009-09-09 15:08:12 +00005906
Steve Naroff8e6aee52009-07-23 01:01:38 +00005907 return true;
5908 }
Mike Stump11289f42009-09-09 15:08:12 +00005909
Steve Naroff8e6aee52009-07-23 01:01:38 +00005910 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5911 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5912
Mike Stump11289f42009-09-09 15:08:12 +00005913 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005914 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005915 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005916 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5917 E = lhsOPT->qual_end(); I != E; ++I) {
5918 ObjCProtocolDecl *lhsProto = *I;
5919 bool match = false;
5920
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005921 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005922 // see if static class implements all of id's protocols, directly or
5923 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005924 // First, lhs protocols in the qualifier list must be found, direct
5925 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005926 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5927 E = rhsQID->qual_end(); J != E; ++J) {
5928 ObjCProtocolDecl *rhsProto = *J;
5929 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5930 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5931 match = true;
5932 break;
5933 }
5934 }
5935 if (!match)
5936 return false;
5937 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005938
5939 // Static class's protocols, or its super class or category protocols
5940 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5941 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5942 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5943 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5944 // This is rather dubious but matches gcc's behavior. If lhs has
5945 // no type qualifier and its class has no static protocol(s)
5946 // assume that it is mismatch.
5947 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5948 return false;
5949 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5950 LHSInheritedProtocols.begin(),
5951 E = LHSInheritedProtocols.end(); I != E; ++I) {
5952 bool match = false;
5953 ObjCProtocolDecl *lhsProto = (*I);
5954 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5955 E = rhsQID->qual_end(); J != E; ++J) {
5956 ObjCProtocolDecl *rhsProto = *J;
5957 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5958 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5959 match = true;
5960 break;
5961 }
5962 }
5963 if (!match)
5964 return false;
5965 }
5966 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005967 return true;
5968 }
5969 return false;
5970}
5971
Eli Friedman47f77112008-08-22 00:56:42 +00005972/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005973/// compatible for assignment from RHS to LHS. This handles validation of any
5974/// protocol qualifiers on the LHS or RHS.
5975///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005976bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5977 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005978 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5979 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5980
Steve Naroff1329fa02009-07-15 18:40:39 +00005981 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005982 if (LHS->isObjCUnqualifiedIdOrClass() ||
5983 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005984 return true;
5985
John McCall8b07ec22010-05-15 11:32:37 +00005986 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005987 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5988 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005989 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005990
5991 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5992 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5993 QualType(RHSOPT,0));
5994
John McCall8b07ec22010-05-15 11:32:37 +00005995 // If we have 2 user-defined types, fall into that path.
5996 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005997 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005998
Steve Naroff8e6aee52009-07-23 01:01:38 +00005999 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006000}
6001
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006002/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006003/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006004/// arguments in block literals. When passed as arguments, passing 'A*' where
6005/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6006/// not OK. For the return type, the opposite is not OK.
6007bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6008 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006009 const ObjCObjectPointerType *RHSOPT,
6010 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006011 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006012 return true;
6013
6014 if (LHSOPT->isObjCBuiltinType()) {
6015 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6016 }
6017
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006018 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006019 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6020 QualType(RHSOPT,0),
6021 false);
6022
6023 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6024 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6025 if (LHS && RHS) { // We have 2 user-defined types.
6026 if (LHS != RHS) {
6027 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006028 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006029 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006030 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006031 }
6032 else
6033 return true;
6034 }
6035 return false;
6036}
6037
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006038/// getIntersectionOfProtocols - This routine finds the intersection of set
6039/// of protocols inherited from two distinct objective-c pointer objects.
6040/// It is used to build composite qualifier list of the composite type of
6041/// the conditional expression involving two objective-c pointer objects.
6042static
6043void getIntersectionOfProtocols(ASTContext &Context,
6044 const ObjCObjectPointerType *LHSOPT,
6045 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006046 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006047
John McCall8b07ec22010-05-15 11:32:37 +00006048 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6049 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6050 assert(LHS->getInterface() && "LHS must have an interface base");
6051 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006052
6053 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6054 unsigned LHSNumProtocols = LHS->getNumProtocols();
6055 if (LHSNumProtocols > 0)
6056 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6057 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006058 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006059 Context.CollectInheritedProtocols(LHS->getInterface(),
6060 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006061 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6062 LHSInheritedProtocols.end());
6063 }
6064
6065 unsigned RHSNumProtocols = RHS->getNumProtocols();
6066 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006067 ObjCProtocolDecl **RHSProtocols =
6068 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006069 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6070 if (InheritedProtocolSet.count(RHSProtocols[i]))
6071 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006072 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006073 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006074 Context.CollectInheritedProtocols(RHS->getInterface(),
6075 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006076 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6077 RHSInheritedProtocols.begin(),
6078 E = RHSInheritedProtocols.end(); I != E; ++I)
6079 if (InheritedProtocolSet.count((*I)))
6080 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006081 }
6082}
6083
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006084/// areCommonBaseCompatible - Returns common base class of the two classes if
6085/// one found. Note that this is O'2 algorithm. But it will be called as the
6086/// last type comparison in a ?-exp of ObjC pointer types before a
6087/// warning is issued. So, its invokation is extremely rare.
6088QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006089 const ObjCObjectPointerType *Lptr,
6090 const ObjCObjectPointerType *Rptr) {
6091 const ObjCObjectType *LHS = Lptr->getObjectType();
6092 const ObjCObjectType *RHS = Rptr->getObjectType();
6093 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6094 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006095 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006096 return QualType();
6097
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006098 do {
John McCall8b07ec22010-05-15 11:32:37 +00006099 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006100 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006101 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006102 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6103
6104 QualType Result = QualType(LHS, 0);
6105 if (!Protocols.empty())
6106 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6107 Result = getObjCObjectPointerType(Result);
6108 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006109 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006110 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006111
6112 return QualType();
6113}
6114
John McCall8b07ec22010-05-15 11:32:37 +00006115bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6116 const ObjCObjectType *RHS) {
6117 assert(LHS->getInterface() && "LHS is not an interface type");
6118 assert(RHS->getInterface() && "RHS is not an interface type");
6119
Chris Lattner49af6a42008-04-07 06:51:04 +00006120 // Verify that the base decls are compatible: the RHS must be a subclass of
6121 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006122 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006123 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006124
Chris Lattner49af6a42008-04-07 06:51:04 +00006125 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6126 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006127 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006128 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006129
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006130 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6131 // more detailed analysis is required.
6132 if (RHS->getNumProtocols() == 0) {
6133 // OK, if LHS is a superclass of RHS *and*
6134 // this superclass is assignment compatible with LHS.
6135 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006136 bool IsSuperClass =
6137 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6138 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006139 // OK if conversion of LHS to SuperClass results in narrowing of types
6140 // ; i.e., SuperClass may implement at least one of the protocols
6141 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6142 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6143 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006144 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006145 // If super class has no protocols, it is not a match.
6146 if (SuperClassInheritedProtocols.empty())
6147 return false;
6148
6149 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6150 LHSPE = LHS->qual_end();
6151 LHSPI != LHSPE; LHSPI++) {
6152 bool SuperImplementsProtocol = false;
6153 ObjCProtocolDecl *LHSProto = (*LHSPI);
6154
6155 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6156 SuperClassInheritedProtocols.begin(),
6157 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6158 ObjCProtocolDecl *SuperClassProto = (*I);
6159 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6160 SuperImplementsProtocol = true;
6161 break;
6162 }
6163 }
6164 if (!SuperImplementsProtocol)
6165 return false;
6166 }
6167 return true;
6168 }
6169 return false;
6170 }
Mike Stump11289f42009-09-09 15:08:12 +00006171
John McCall8b07ec22010-05-15 11:32:37 +00006172 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6173 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006174 LHSPI != LHSPE; LHSPI++) {
6175 bool RHSImplementsProtocol = false;
6176
6177 // If the RHS doesn't implement the protocol on the left, the types
6178 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006179 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6180 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006181 RHSPI != RHSPE; RHSPI++) {
6182 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006183 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006184 break;
6185 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006186 }
6187 // FIXME: For better diagnostics, consider passing back the protocol name.
6188 if (!RHSImplementsProtocol)
6189 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006190 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006191 // The RHS implements all protocols listed on the LHS.
6192 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006193}
6194
Steve Naroffb7605152009-02-12 17:52:19 +00006195bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6196 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006197 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6198 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006199
Steve Naroff7cae42b2009-07-10 23:34:53 +00006200 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006201 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006202
6203 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6204 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006205}
6206
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006207bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6208 return canAssignObjCInterfaces(
6209 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6210 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6211}
6212
Mike Stump11289f42009-09-09 15:08:12 +00006213/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006214/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006215/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006216/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006217bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6218 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006219 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006220 return hasSameType(LHS, RHS);
6221
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006222 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006223}
6224
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006225bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006226 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006227}
6228
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006229bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6230 return !mergeTypes(LHS, RHS, true).isNull();
6231}
6232
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006233/// mergeTransparentUnionType - if T is a transparent union type and a member
6234/// of T is compatible with SubType, return the merged type, else return
6235/// QualType()
6236QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6237 bool OfBlockPointer,
6238 bool Unqualified) {
6239 if (const RecordType *UT = T->getAsUnionType()) {
6240 RecordDecl *UD = UT->getDecl();
6241 if (UD->hasAttr<TransparentUnionAttr>()) {
6242 for (RecordDecl::field_iterator it = UD->field_begin(),
6243 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006244 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006245 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6246 if (!MT.isNull())
6247 return MT;
6248 }
6249 }
6250 }
6251
6252 return QualType();
6253}
6254
6255/// mergeFunctionArgumentTypes - merge two types which appear as function
6256/// argument types
6257QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6258 bool OfBlockPointer,
6259 bool Unqualified) {
6260 // GNU extension: two types are compatible if they appear as a function
6261 // argument, one of the types is a transparent union type and the other
6262 // type is compatible with a union member
6263 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6264 Unqualified);
6265 if (!lmerge.isNull())
6266 return lmerge;
6267
6268 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6269 Unqualified);
6270 if (!rmerge.isNull())
6271 return rmerge;
6272
6273 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6274}
6275
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006276QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006277 bool OfBlockPointer,
6278 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006279 const FunctionType *lbase = lhs->getAs<FunctionType>();
6280 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006281 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6282 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006283 bool allLTypes = true;
6284 bool allRTypes = true;
6285
6286 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006287 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006288 if (OfBlockPointer) {
6289 QualType RHS = rbase->getResultType();
6290 QualType LHS = lbase->getResultType();
6291 bool UnqualifiedResult = Unqualified;
6292 if (!UnqualifiedResult)
6293 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006294 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006295 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006296 else
John McCall8c6b56f2010-12-15 01:06:38 +00006297 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6298 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006299 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006300
6301 if (Unqualified)
6302 retType = retType.getUnqualifiedType();
6303
6304 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6305 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6306 if (Unqualified) {
6307 LRetType = LRetType.getUnqualifiedType();
6308 RRetType = RRetType.getUnqualifiedType();
6309 }
6310
6311 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006312 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006313 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006314 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006315
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006316 // FIXME: double check this
6317 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6318 // rbase->getRegParmAttr() != 0 &&
6319 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006320 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6321 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006322
Douglas Gregor8c940862010-01-18 17:14:39 +00006323 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006324 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006325 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006326
John McCall8c6b56f2010-12-15 01:06:38 +00006327 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006328 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6329 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006330 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6331 return QualType();
6332
John McCall31168b02011-06-15 23:02:42 +00006333 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6334 return QualType();
6335
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006336 // functypes which return are preferred over those that do not.
6337 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6338 allLTypes = false;
6339 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6340 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006341 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6342 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006343
John McCall31168b02011-06-15 23:02:42 +00006344 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006345
Eli Friedman47f77112008-08-22 00:56:42 +00006346 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006347 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6348 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006349 unsigned lproto_nargs = lproto->getNumArgs();
6350 unsigned rproto_nargs = rproto->getNumArgs();
6351
6352 // Compatible functions must have the same number of arguments
6353 if (lproto_nargs != rproto_nargs)
6354 return QualType();
6355
6356 // Variadic and non-variadic functions aren't compatible
6357 if (lproto->isVariadic() != rproto->isVariadic())
6358 return QualType();
6359
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006360 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6361 return QualType();
6362
Fariborz Jahanian97676972011-09-28 21:52:05 +00006363 if (LangOpts.ObjCAutoRefCount &&
6364 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6365 return QualType();
6366
Eli Friedman47f77112008-08-22 00:56:42 +00006367 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006368 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006369 for (unsigned i = 0; i < lproto_nargs; i++) {
6370 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6371 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006372 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6373 OfBlockPointer,
6374 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006375 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006376
6377 if (Unqualified)
6378 argtype = argtype.getUnqualifiedType();
6379
Eli Friedman47f77112008-08-22 00:56:42 +00006380 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006381 if (Unqualified) {
6382 largtype = largtype.getUnqualifiedType();
6383 rargtype = rargtype.getUnqualifiedType();
6384 }
6385
Chris Lattner465fa322008-10-05 17:34:18 +00006386 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6387 allLTypes = false;
6388 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6389 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006390 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006391
Eli Friedman47f77112008-08-22 00:56:42 +00006392 if (allLTypes) return lhs;
6393 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006394
6395 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6396 EPI.ExtInfo = einfo;
6397 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006398 }
6399
6400 if (lproto) allRTypes = false;
6401 if (rproto) allLTypes = false;
6402
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006403 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006404 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006405 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006406 if (proto->isVariadic()) return QualType();
6407 // Check that the types are compatible with the types that
6408 // would result from default argument promotions (C99 6.7.5.3p15).
6409 // The only types actually affected are promotable integer
6410 // types and floats, which would be passed as a different
6411 // type depending on whether the prototype is visible.
6412 unsigned proto_nargs = proto->getNumArgs();
6413 for (unsigned i = 0; i < proto_nargs; ++i) {
6414 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006415
6416 // Look at the promotion type of enum types, since that is the type used
6417 // to pass enum values.
6418 if (const EnumType *Enum = argTy->getAs<EnumType>())
6419 argTy = Enum->getDecl()->getPromotionType();
6420
Eli Friedman47f77112008-08-22 00:56:42 +00006421 if (argTy->isPromotableIntegerType() ||
6422 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6423 return QualType();
6424 }
6425
6426 if (allLTypes) return lhs;
6427 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006428
6429 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6430 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006431 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006432 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006433 }
6434
6435 if (allLTypes) return lhs;
6436 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006437 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006438}
6439
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006440QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006441 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006442 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006443 // C++ [expr]: If an expression initially has the type "reference to T", the
6444 // type is adjusted to "T" prior to any further analysis, the expression
6445 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006446 // expression is an lvalue unless the reference is an rvalue reference and
6447 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006448 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6449 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006450
6451 if (Unqualified) {
6452 LHS = LHS.getUnqualifiedType();
6453 RHS = RHS.getUnqualifiedType();
6454 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006455
Eli Friedman47f77112008-08-22 00:56:42 +00006456 QualType LHSCan = getCanonicalType(LHS),
6457 RHSCan = getCanonicalType(RHS);
6458
6459 // If two types are identical, they are compatible.
6460 if (LHSCan == RHSCan)
6461 return LHS;
6462
John McCall8ccfcb52009-09-24 19:53:00 +00006463 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006464 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6465 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006466 if (LQuals != RQuals) {
6467 // If any of these qualifiers are different, we have a type
6468 // mismatch.
6469 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006470 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6471 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006472 return QualType();
6473
6474 // Exactly one GC qualifier difference is allowed: __strong is
6475 // okay if the other type has no GC qualifier but is an Objective
6476 // C object pointer (i.e. implicitly strong by default). We fix
6477 // this by pretending that the unqualified type was actually
6478 // qualified __strong.
6479 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6480 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6481 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6482
6483 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6484 return QualType();
6485
6486 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6487 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6488 }
6489 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6490 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6491 }
Eli Friedman47f77112008-08-22 00:56:42 +00006492 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006493 }
6494
6495 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006496
Eli Friedmandcca6332009-06-01 01:22:52 +00006497 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6498 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006499
Chris Lattnerfd652912008-01-14 05:45:46 +00006500 // We want to consider the two function types to be the same for these
6501 // comparisons, just force one to the other.
6502 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6503 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006504
6505 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006506 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6507 LHSClass = Type::ConstantArray;
6508 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6509 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006510
John McCall8b07ec22010-05-15 11:32:37 +00006511 // ObjCInterfaces are just specialized ObjCObjects.
6512 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6513 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6514
Nate Begemance4d7fc2008-04-18 23:10:10 +00006515 // Canonicalize ExtVector -> Vector.
6516 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6517 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006518
Chris Lattner95554662008-04-07 05:43:21 +00006519 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006520 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006521 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006522 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006523 // Compatibility is based on the underlying type, not the promotion
6524 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006525 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006526 QualType TINT = ETy->getDecl()->getIntegerType();
6527 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006528 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006529 }
John McCall9dd450b2009-09-21 23:43:11 +00006530 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006531 QualType TINT = ETy->getDecl()->getIntegerType();
6532 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006533 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006534 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006535 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006536 if (OfBlockPointer && !BlockReturnType) {
6537 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6538 return LHS;
6539 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6540 return RHS;
6541 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006542
Eli Friedman47f77112008-08-22 00:56:42 +00006543 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006544 }
Eli Friedman47f77112008-08-22 00:56:42 +00006545
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006546 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006547 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006548#define TYPE(Class, Base)
6549#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006550#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006551#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6552#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6553#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006554 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006555
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006556 case Type::LValueReference:
6557 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006558 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006559 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006560
John McCall8b07ec22010-05-15 11:32:37 +00006561 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006562 case Type::IncompleteArray:
6563 case Type::VariableArray:
6564 case Type::FunctionProto:
6565 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006566 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006567
Chris Lattnerfd652912008-01-14 05:45:46 +00006568 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006569 {
6570 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006571 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6572 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006573 if (Unqualified) {
6574 LHSPointee = LHSPointee.getUnqualifiedType();
6575 RHSPointee = RHSPointee.getUnqualifiedType();
6576 }
6577 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6578 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006579 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006580 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006581 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006582 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006583 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006584 return getPointerType(ResultType);
6585 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006586 case Type::BlockPointer:
6587 {
6588 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006589 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6590 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006591 if (Unqualified) {
6592 LHSPointee = LHSPointee.getUnqualifiedType();
6593 RHSPointee = RHSPointee.getUnqualifiedType();
6594 }
6595 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6596 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006597 if (ResultType.isNull()) return QualType();
6598 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6599 return LHS;
6600 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6601 return RHS;
6602 return getBlockPointerType(ResultType);
6603 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006604 case Type::Atomic:
6605 {
6606 // Merge two pointer types, while trying to preserve typedef info
6607 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6608 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6609 if (Unqualified) {
6610 LHSValue = LHSValue.getUnqualifiedType();
6611 RHSValue = RHSValue.getUnqualifiedType();
6612 }
6613 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6614 Unqualified);
6615 if (ResultType.isNull()) return QualType();
6616 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6617 return LHS;
6618 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6619 return RHS;
6620 return getAtomicType(ResultType);
6621 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006622 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006623 {
6624 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6625 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6626 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6627 return QualType();
6628
6629 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6630 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006631 if (Unqualified) {
6632 LHSElem = LHSElem.getUnqualifiedType();
6633 RHSElem = RHSElem.getUnqualifiedType();
6634 }
6635
6636 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006637 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006638 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6639 return LHS;
6640 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6641 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006642 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6643 ArrayType::ArraySizeModifier(), 0);
6644 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6645 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006646 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6647 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006648 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6649 return LHS;
6650 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6651 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006652 if (LVAT) {
6653 // FIXME: This isn't correct! But tricky to implement because
6654 // the array's size has to be the size of LHS, but the type
6655 // has to be different.
6656 return LHS;
6657 }
6658 if (RVAT) {
6659 // FIXME: This isn't correct! But tricky to implement because
6660 // the array's size has to be the size of RHS, but the type
6661 // has to be different.
6662 return RHS;
6663 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006664 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6665 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006666 return getIncompleteArrayType(ResultType,
6667 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006668 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006669 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006670 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006671 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006672 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006673 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006674 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006675 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006676 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006677 case Type::Complex:
6678 // Distinct complex types are incompatible.
6679 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006680 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006681 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006682 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6683 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006684 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006685 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006686 case Type::ObjCObject: {
6687 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006688 // FIXME: This should be type compatibility, e.g. whether
6689 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006690 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6691 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6692 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006693 return LHS;
6694
Eli Friedman47f77112008-08-22 00:56:42 +00006695 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006696 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006697 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006698 if (OfBlockPointer) {
6699 if (canAssignObjCInterfacesInBlockPointer(
6700 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006701 RHS->getAs<ObjCObjectPointerType>(),
6702 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006703 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006704 return QualType();
6705 }
John McCall9dd450b2009-09-21 23:43:11 +00006706 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6707 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006708 return LHS;
6709
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006710 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006711 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006712 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006713
David Blaikie8a40f702012-01-17 06:56:22 +00006714 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006715}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006716
Fariborz Jahanian97676972011-09-28 21:52:05 +00006717bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6718 const FunctionProtoType *FromFunctionType,
6719 const FunctionProtoType *ToFunctionType) {
6720 if (FromFunctionType->hasAnyConsumedArgs() !=
6721 ToFunctionType->hasAnyConsumedArgs())
6722 return false;
6723 FunctionProtoType::ExtProtoInfo FromEPI =
6724 FromFunctionType->getExtProtoInfo();
6725 FunctionProtoType::ExtProtoInfo ToEPI =
6726 ToFunctionType->getExtProtoInfo();
6727 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6728 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6729 ArgIdx != NumArgs; ++ArgIdx) {
6730 if (FromEPI.ConsumedArguments[ArgIdx] !=
6731 ToEPI.ConsumedArguments[ArgIdx])
6732 return false;
6733 }
6734 return true;
6735}
6736
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006737/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6738/// 'RHS' attributes and returns the merged version; including for function
6739/// return types.
6740QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6741 QualType LHSCan = getCanonicalType(LHS),
6742 RHSCan = getCanonicalType(RHS);
6743 // If two types are identical, they are compatible.
6744 if (LHSCan == RHSCan)
6745 return LHS;
6746 if (RHSCan->isFunctionType()) {
6747 if (!LHSCan->isFunctionType())
6748 return QualType();
6749 QualType OldReturnType =
6750 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6751 QualType NewReturnType =
6752 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6753 QualType ResReturnType =
6754 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6755 if (ResReturnType.isNull())
6756 return QualType();
6757 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6758 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6759 // In either case, use OldReturnType to build the new function type.
6760 const FunctionType *F = LHS->getAs<FunctionType>();
6761 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006762 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6763 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006764 QualType ResultType
6765 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006766 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006767 return ResultType;
6768 }
6769 }
6770 return QualType();
6771 }
6772
6773 // If the qualifiers are different, the types can still be merged.
6774 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6775 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6776 if (LQuals != RQuals) {
6777 // If any of these qualifiers are different, we have a type mismatch.
6778 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6779 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6780 return QualType();
6781
6782 // Exactly one GC qualifier difference is allowed: __strong is
6783 // okay if the other type has no GC qualifier but is an Objective
6784 // C object pointer (i.e. implicitly strong by default). We fix
6785 // this by pretending that the unqualified type was actually
6786 // qualified __strong.
6787 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6788 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6789 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6790
6791 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6792 return QualType();
6793
6794 if (GC_L == Qualifiers::Strong)
6795 return LHS;
6796 if (GC_R == Qualifiers::Strong)
6797 return RHS;
6798 return QualType();
6799 }
6800
6801 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6802 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6803 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6804 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6805 if (ResQT == LHSBaseQT)
6806 return LHS;
6807 if (ResQT == RHSBaseQT)
6808 return RHS;
6809 }
6810 return QualType();
6811}
6812
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006813//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006814// Integer Predicates
6815//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006816
Jay Foad39c79802011-01-12 09:06:06 +00006817unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006818 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006819 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006820 if (T->isBooleanType())
6821 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006822 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006823 return (unsigned)getTypeSize(T);
6824}
6825
6826QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006827 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006828
6829 // Turn <4 x signed int> -> <4 x unsigned int>
6830 if (const VectorType *VTy = T->getAs<VectorType>())
6831 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006832 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006833
6834 // For enums, we return the unsigned version of the base type.
6835 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006836 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006837
6838 const BuiltinType *BTy = T->getAs<BuiltinType>();
6839 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006840 switch (BTy->getKind()) {
6841 case BuiltinType::Char_S:
6842 case BuiltinType::SChar:
6843 return UnsignedCharTy;
6844 case BuiltinType::Short:
6845 return UnsignedShortTy;
6846 case BuiltinType::Int:
6847 return UnsignedIntTy;
6848 case BuiltinType::Long:
6849 return UnsignedLongTy;
6850 case BuiltinType::LongLong:
6851 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006852 case BuiltinType::Int128:
6853 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006854 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006855 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006856 }
6857}
6858
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006859ASTMutationListener::~ASTMutationListener() { }
6860
Chris Lattnerecd79c62009-06-14 00:45:47 +00006861
6862//===----------------------------------------------------------------------===//
6863// Builtin Type Computation
6864//===----------------------------------------------------------------------===//
6865
6866/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006867/// pointer over the consumed characters. This returns the resultant type. If
6868/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6869/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6870/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006871///
6872/// RequiresICE is filled in on return to indicate whether the value is required
6873/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006874static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006875 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006876 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006877 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006878 // Modifiers.
6879 int HowLong = 0;
6880 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006881 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006882
Chris Lattnerdc226c22010-10-01 22:42:38 +00006883 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006884 bool Done = false;
6885 while (!Done) {
6886 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006887 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006888 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006889 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006890 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006891 case 'S':
6892 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6893 assert(!Signed && "Can't use 'S' modifier multiple times!");
6894 Signed = true;
6895 break;
6896 case 'U':
6897 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6898 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6899 Unsigned = true;
6900 break;
6901 case 'L':
6902 assert(HowLong <= 2 && "Can't have LLLL modifier");
6903 ++HowLong;
6904 break;
6905 }
6906 }
6907
6908 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006909
Chris Lattnerecd79c62009-06-14 00:45:47 +00006910 // Read the base type.
6911 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006912 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006913 case 'v':
6914 assert(HowLong == 0 && !Signed && !Unsigned &&
6915 "Bad modifiers used with 'v'!");
6916 Type = Context.VoidTy;
6917 break;
6918 case 'f':
6919 assert(HowLong == 0 && !Signed && !Unsigned &&
6920 "Bad modifiers used with 'f'!");
6921 Type = Context.FloatTy;
6922 break;
6923 case 'd':
6924 assert(HowLong < 2 && !Signed && !Unsigned &&
6925 "Bad modifiers used with 'd'!");
6926 if (HowLong)
6927 Type = Context.LongDoubleTy;
6928 else
6929 Type = Context.DoubleTy;
6930 break;
6931 case 's':
6932 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6933 if (Unsigned)
6934 Type = Context.UnsignedShortTy;
6935 else
6936 Type = Context.ShortTy;
6937 break;
6938 case 'i':
6939 if (HowLong == 3)
6940 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6941 else if (HowLong == 2)
6942 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6943 else if (HowLong == 1)
6944 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6945 else
6946 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6947 break;
6948 case 'c':
6949 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6950 if (Signed)
6951 Type = Context.SignedCharTy;
6952 else if (Unsigned)
6953 Type = Context.UnsignedCharTy;
6954 else
6955 Type = Context.CharTy;
6956 break;
6957 case 'b': // boolean
6958 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6959 Type = Context.BoolTy;
6960 break;
6961 case 'z': // size_t.
6962 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6963 Type = Context.getSizeType();
6964 break;
6965 case 'F':
6966 Type = Context.getCFConstantStringType();
6967 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006968 case 'G':
6969 Type = Context.getObjCIdType();
6970 break;
6971 case 'H':
6972 Type = Context.getObjCSelType();
6973 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006974 case 'a':
6975 Type = Context.getBuiltinVaListType();
6976 assert(!Type.isNull() && "builtin va list type not initialized!");
6977 break;
6978 case 'A':
6979 // This is a "reference" to a va_list; however, what exactly
6980 // this means depends on how va_list is defined. There are two
6981 // different kinds of va_list: ones passed by value, and ones
6982 // passed by reference. An example of a by-value va_list is
6983 // x86, where va_list is a char*. An example of by-ref va_list
6984 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6985 // we want this argument to be a char*&; for x86-64, we want
6986 // it to be a __va_list_tag*.
6987 Type = Context.getBuiltinVaListType();
6988 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006989 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006990 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006991 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006992 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006993 break;
6994 case 'V': {
6995 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006996 unsigned NumElements = strtoul(Str, &End, 10);
6997 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006998 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006999
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007000 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7001 RequiresICE, false);
7002 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007003
7004 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007005 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007006 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007007 break;
7008 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007009 case 'E': {
7010 char *End;
7011
7012 unsigned NumElements = strtoul(Str, &End, 10);
7013 assert(End != Str && "Missing vector size");
7014
7015 Str = End;
7016
7017 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7018 false);
7019 Type = Context.getExtVectorType(ElementType, NumElements);
7020 break;
7021 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007022 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007023 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7024 false);
7025 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007026 Type = Context.getComplexType(ElementType);
7027 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007028 }
7029 case 'Y' : {
7030 Type = Context.getPointerDiffType();
7031 break;
7032 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007033 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007034 Type = Context.getFILEType();
7035 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007036 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007037 return QualType();
7038 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007039 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007040 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007041 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007042 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007043 else
7044 Type = Context.getjmp_bufType();
7045
Mike Stump2adb4da2009-07-28 23:47:15 +00007046 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007047 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007048 return QualType();
7049 }
7050 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007051 case 'K':
7052 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7053 Type = Context.getucontext_tType();
7054
7055 if (Type.isNull()) {
7056 Error = ASTContext::GE_Missing_ucontext;
7057 return QualType();
7058 }
7059 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007060 }
Mike Stump11289f42009-09-09 15:08:12 +00007061
Chris Lattnerdc226c22010-10-01 22:42:38 +00007062 // If there are modifiers and if we're allowed to parse them, go for it.
7063 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007064 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007065 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007066 default: Done = true; --Str; break;
7067 case '*':
7068 case '&': {
7069 // Both pointers and references can have their pointee types
7070 // qualified with an address space.
7071 char *End;
7072 unsigned AddrSpace = strtoul(Str, &End, 10);
7073 if (End != Str && AddrSpace != 0) {
7074 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7075 Str = End;
7076 }
7077 if (c == '*')
7078 Type = Context.getPointerType(Type);
7079 else
7080 Type = Context.getLValueReferenceType(Type);
7081 break;
7082 }
7083 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7084 case 'C':
7085 Type = Type.withConst();
7086 break;
7087 case 'D':
7088 Type = Context.getVolatileType(Type);
7089 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007090 case 'R':
7091 Type = Type.withRestrict();
7092 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007093 }
7094 }
Chris Lattner84733392010-10-01 07:13:18 +00007095
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007096 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007097 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007098
Chris Lattnerecd79c62009-06-14 00:45:47 +00007099 return Type;
7100}
7101
7102/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007103QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007104 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007105 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007106 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007107
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007108 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007109
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007110 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007111 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007112 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7113 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007114 if (Error != GE_None)
7115 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007116
7117 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7118
Chris Lattnerecd79c62009-06-14 00:45:47 +00007119 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007120 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007121 if (Error != GE_None)
7122 return QualType();
7123
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007124 // If this argument is required to be an IntegerConstantExpression and the
7125 // caller cares, fill in the bitmask we return.
7126 if (RequiresICE && IntegerConstantArgs)
7127 *IntegerConstantArgs |= 1 << ArgTypes.size();
7128
Chris Lattnerecd79c62009-06-14 00:45:47 +00007129 // Do array -> pointer decay. The builtin should use the decayed type.
7130 if (Ty->isArrayType())
7131 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007132
Chris Lattnerecd79c62009-06-14 00:45:47 +00007133 ArgTypes.push_back(Ty);
7134 }
7135
7136 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7137 "'.' should only occur at end of builtin type list!");
7138
John McCall991eb4b2010-12-21 00:44:39 +00007139 FunctionType::ExtInfo EI;
7140 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7141
7142 bool Variadic = (TypeStr[0] == '.');
7143
7144 // We really shouldn't be making a no-proto type here, especially in C++.
7145 if (ArgTypes.empty() && Variadic)
7146 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007147
John McCalldb40c7f2010-12-14 08:05:40 +00007148 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007149 EPI.ExtInfo = EI;
7150 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007151
7152 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007153}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007154
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007155GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7156 GVALinkage External = GVA_StrongExternal;
7157
7158 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007159 switch (L) {
7160 case NoLinkage:
7161 case InternalLinkage:
7162 case UniqueExternalLinkage:
7163 return GVA_Internal;
7164
7165 case ExternalLinkage:
7166 switch (FD->getTemplateSpecializationKind()) {
7167 case TSK_Undeclared:
7168 case TSK_ExplicitSpecialization:
7169 External = GVA_StrongExternal;
7170 break;
7171
7172 case TSK_ExplicitInstantiationDefinition:
7173 return GVA_ExplicitTemplateInstantiation;
7174
7175 case TSK_ExplicitInstantiationDeclaration:
7176 case TSK_ImplicitInstantiation:
7177 External = GVA_TemplateInstantiation;
7178 break;
7179 }
7180 }
7181
7182 if (!FD->isInlined())
7183 return External;
7184
David Blaikiebbafb8a2012-03-11 07:00:24 +00007185 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007186 // GNU or C99 inline semantics. Determine whether this symbol should be
7187 // externally visible.
7188 if (FD->isInlineDefinitionExternallyVisible())
7189 return External;
7190
7191 // C99 inline semantics, where the symbol is not externally visible.
7192 return GVA_C99Inline;
7193 }
7194
7195 // C++0x [temp.explicit]p9:
7196 // [ Note: The intent is that an inline function that is the subject of
7197 // an explicit instantiation declaration will still be implicitly
7198 // instantiated when used so that the body can be considered for
7199 // inlining, but that no out-of-line copy of the inline function would be
7200 // generated in the translation unit. -- end note ]
7201 if (FD->getTemplateSpecializationKind()
7202 == TSK_ExplicitInstantiationDeclaration)
7203 return GVA_C99Inline;
7204
7205 return GVA_CXXInline;
7206}
7207
7208GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7209 // If this is a static data member, compute the kind of template
7210 // specialization. Otherwise, this variable is not part of a
7211 // template.
7212 TemplateSpecializationKind TSK = TSK_Undeclared;
7213 if (VD->isStaticDataMember())
7214 TSK = VD->getTemplateSpecializationKind();
7215
7216 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007217 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007218 VD->getType()->getLinkage() == UniqueExternalLinkage)
7219 L = UniqueExternalLinkage;
7220
7221 switch (L) {
7222 case NoLinkage:
7223 case InternalLinkage:
7224 case UniqueExternalLinkage:
7225 return GVA_Internal;
7226
7227 case ExternalLinkage:
7228 switch (TSK) {
7229 case TSK_Undeclared:
7230 case TSK_ExplicitSpecialization:
7231 return GVA_StrongExternal;
7232
7233 case TSK_ExplicitInstantiationDeclaration:
7234 llvm_unreachable("Variable should not be instantiated");
7235 // Fall through to treat this like any other instantiation.
7236
7237 case TSK_ExplicitInstantiationDefinition:
7238 return GVA_ExplicitTemplateInstantiation;
7239
7240 case TSK_ImplicitInstantiation:
7241 return GVA_TemplateInstantiation;
7242 }
7243 }
7244
David Blaikie8a40f702012-01-17 06:56:22 +00007245 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007246}
7247
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007248bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007249 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7250 if (!VD->isFileVarDecl())
7251 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007252 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007253 return false;
7254
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007255 // Weak references don't produce any output by themselves.
7256 if (D->hasAttr<WeakRefAttr>())
7257 return false;
7258
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007259 // Aliases and used decls are required.
7260 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7261 return true;
7262
7263 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7264 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007265 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007266 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007267
7268 // Constructors and destructors are required.
7269 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7270 return true;
7271
7272 // The key function for a class is required.
7273 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7274 const CXXRecordDecl *RD = MD->getParent();
7275 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7276 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7277 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7278 return true;
7279 }
7280 }
7281
7282 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7283
7284 // static, static inline, always_inline, and extern inline functions can
7285 // always be deferred. Normal inline functions can be deferred in C99/C++.
7286 // Implicit template instantiations can also be deferred in C++.
7287 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007288 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007289 return false;
7290 return true;
7291 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007292
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007293 const VarDecl *VD = cast<VarDecl>(D);
7294 assert(VD->isFileVarDecl() && "Expected file scoped var");
7295
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007296 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7297 return false;
7298
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007299 // Structs that have non-trivial constructors or destructors are required.
7300
7301 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007302 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007303 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7304 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007305 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7306 RD->hasTrivialCopyConstructor() &&
7307 RD->hasTrivialMoveConstructor() &&
7308 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007309 return true;
7310 }
7311 }
7312
7313 GVALinkage L = GetGVALinkageForVariable(VD);
7314 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7315 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7316 return false;
7317 }
7318
7319 return true;
7320}
Charles Davis53c59df2010-08-16 03:33:14 +00007321
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007322CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007323 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007324 return ABI->getDefaultMethodCallConv(isVariadic);
7325}
7326
7327CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7328 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7329 return CC_Default;
7330 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007331}
7332
Jay Foad39c79802011-01-12 09:06:06 +00007333bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007334 // Pass through to the C++ ABI object
7335 return ABI->isNearlyEmpty(RD);
7336}
7337
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007338MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007339 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007340 case CXXABI_ARM:
7341 case CXXABI_Itanium:
7342 return createItaniumMangleContext(*this, getDiagnostics());
7343 case CXXABI_Microsoft:
7344 return createMicrosoftMangleContext(*this, getDiagnostics());
7345 }
David Blaikie83d382b2011-09-23 05:06:16 +00007346 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007347}
7348
Charles Davis53c59df2010-08-16 03:33:14 +00007349CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007350
7351size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007352 return ASTRecordLayouts.getMemorySize()
7353 + llvm::capacity_in_bytes(ObjCLayouts)
7354 + llvm::capacity_in_bytes(KeyFunctions)
7355 + llvm::capacity_in_bytes(ObjCImpls)
7356 + llvm::capacity_in_bytes(BlockVarCopyInits)
7357 + llvm::capacity_in_bytes(DeclAttrs)
7358 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7359 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7360 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7361 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7362 + llvm::capacity_in_bytes(OverriddenMethods)
7363 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007364 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007365 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007366}
Ted Kremenek540017e2011-10-06 05:00:56 +00007367
Douglas Gregor63798542012-02-20 19:44:39 +00007368unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7369 CXXRecordDecl *Lambda = CallOperator->getParent();
7370 return LambdaMangleContexts[Lambda->getDeclContext()]
7371 .getManglingNumber(CallOperator);
7372}
7373
7374
Ted Kremenek540017e2011-10-06 05:00:56 +00007375void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7376 ParamIndices[D] = index;
7377}
7378
7379unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7380 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7381 assert(I != ParamIndices.end() &&
7382 "ParmIndices lacks entry set by ParmVarDecl");
7383 return I->second;
7384}