blob: 83f3f9ca119c254cf0267b6f951535d0151b5244 [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 Gribenko6743e042012-09-29 11:40:46 +0000358comments::FullComment *ASTContext::getCommentForDecl(
359 const Decl *D,
360 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000361 D = adjustDeclToTemplate(D);
362 const Decl *Canonical = D->getCanonicalDecl();
363 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
364 ParsedComments.find(Canonical);
365 if (Pos != ParsedComments.end())
366 return Pos->second;
367
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000368 const Decl *OriginalDecl;
369 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000370 if (!RC)
371 return NULL;
372
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000373 // If the RawComment was attached to other redeclaration of this Decl, we
374 // should parse the comment in context of that other Decl. This is important
375 // because comments can contain references to parameter names which can be
376 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000377 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000378 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000379
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000380 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000381 ParsedComments[Canonical] = FC;
382 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000383}
384
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000385void
386ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
387 TemplateTemplateParmDecl *Parm) {
388 ID.AddInteger(Parm->getDepth());
389 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000390 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000391
392 TemplateParameterList *Params = Parm->getTemplateParameters();
393 ID.AddInteger(Params->size());
394 for (TemplateParameterList::const_iterator P = Params->begin(),
395 PEnd = Params->end();
396 P != PEnd; ++P) {
397 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
398 ID.AddInteger(0);
399 ID.AddBoolean(TTP->isParameterPack());
400 continue;
401 }
402
403 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
404 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000405 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000406 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000407 if (NTTP->isExpandedParameterPack()) {
408 ID.AddBoolean(true);
409 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000410 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
411 QualType T = NTTP->getExpansionType(I);
412 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
413 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000414 } else
415 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000416 continue;
417 }
418
419 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
420 ID.AddInteger(2);
421 Profile(ID, TTP);
422 }
423}
424
425TemplateTemplateParmDecl *
426ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000427 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000428 // Check if we already have a canonical template template parameter.
429 llvm::FoldingSetNodeID ID;
430 CanonicalTemplateTemplateParm::Profile(ID, TTP);
431 void *InsertPos = 0;
432 CanonicalTemplateTemplateParm *Canonical
433 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
434 if (Canonical)
435 return Canonical->getParam();
436
437 // Build a canonical template parameter list.
438 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000439 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000440 CanonParams.reserve(Params->size());
441 for (TemplateParameterList::const_iterator P = Params->begin(),
442 PEnd = Params->end();
443 P != PEnd; ++P) {
444 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
445 CanonParams.push_back(
446 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000447 SourceLocation(),
448 SourceLocation(),
449 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000450 TTP->getIndex(), 0, false,
451 TTP->isParameterPack()));
452 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000453 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
454 QualType T = getCanonicalType(NTTP->getType());
455 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
456 NonTypeTemplateParmDecl *Param;
457 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000458 SmallVector<QualType, 2> ExpandedTypes;
459 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000460 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
461 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
462 ExpandedTInfos.push_back(
463 getTrivialTypeSourceInfo(ExpandedTypes.back()));
464 }
465
466 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000467 SourceLocation(),
468 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000469 NTTP->getDepth(),
470 NTTP->getPosition(), 0,
471 T,
472 TInfo,
473 ExpandedTypes.data(),
474 ExpandedTypes.size(),
475 ExpandedTInfos.data());
476 } else {
477 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000478 SourceLocation(),
479 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000480 NTTP->getDepth(),
481 NTTP->getPosition(), 0,
482 T,
483 NTTP->isParameterPack(),
484 TInfo);
485 }
486 CanonParams.push_back(Param);
487
488 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000489 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
490 cast<TemplateTemplateParmDecl>(*P)));
491 }
492
493 TemplateTemplateParmDecl *CanonTTP
494 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
495 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000496 TTP->getPosition(),
497 TTP->isParameterPack(),
498 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000499 TemplateParameterList::Create(*this, SourceLocation(),
500 SourceLocation(),
501 CanonParams.data(),
502 CanonParams.size(),
503 SourceLocation()));
504
505 // Get the new insert position for the node we care about.
506 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
507 assert(Canonical == 0 && "Shouldn't be in the map!");
508 (void)Canonical;
509
510 // Create the canonical template template parameter entry.
511 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
512 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
513 return CanonTTP;
514}
515
Charles Davis53c59df2010-08-16 03:33:14 +0000516CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000517 if (!LangOpts.CPlusPlus) return 0;
518
Charles Davis6bcb07a2010-08-19 02:18:14 +0000519 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000520 case CXXABI_ARM:
521 return CreateARMCXXABI(*this);
522 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000523 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000524 case CXXABI_Microsoft:
525 return CreateMicrosoftCXXABI(*this);
526 }
David Blaikie8a40f702012-01-17 06:56:22 +0000527 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000528}
529
Douglas Gregore8bbc122011-09-02 00:18:52 +0000530static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000531 const LangOptions &LOpts) {
532 if (LOpts.FakeAddressSpaceMap) {
533 // The fake address space map must have a distinct entry for each
534 // language-specific address space.
535 static const unsigned FakeAddrSpaceMap[] = {
536 1, // opencl_global
537 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000538 3, // opencl_constant
539 4, // cuda_device
540 5, // cuda_constant
541 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000542 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000543 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000544 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000545 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000546 }
547}
548
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000549ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000550 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000551 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000552 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000553 unsigned size_reserve,
554 bool DelayInitialization)
555 : FunctionProtoTypes(this_()),
556 TemplateSpecializationTypes(this_()),
557 DependentTemplateSpecializationTypes(this_()),
558 SubstTemplateTemplateParmPacks(this_()),
559 GlobalNestedNameSpecifier(0),
560 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000561 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000562 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000563 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000564 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000565 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000566 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
567 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
568 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000569 NullTypeSourceInfo(QualType()),
570 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000571 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000572 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000573 Idents(idents), Selectors(sels),
574 BuiltinInfo(builtins),
575 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000576 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000577 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000578 CommentCommandTraits(BumpAlloc),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000579 LastSDM(0, 0),
580 UniqueBlockByRefTypeID(0)
581{
Mike Stump11289f42009-09-09 15:08:12 +0000582 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000583 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000584
585 if (!DelayInitialization) {
586 assert(t && "No target supplied for ASTContext initialization");
587 InitBuiltinTypes(*t);
588 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000589}
590
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000591ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000592 // Release the DenseMaps associated with DeclContext objects.
593 // FIXME: Is this the ideal solution?
594 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000595
Douglas Gregor5b11d492010-07-25 17:53:33 +0000596 // Call all of the deallocation functions.
597 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
598 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000599
Ted Kremenek076baeb2010-06-08 23:00:58 +0000600 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000601 // because they can contain DenseMaps.
602 for (llvm::DenseMap<const ObjCContainerDecl*,
603 const ASTRecordLayout*>::iterator
604 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
605 // Increment in loop to prevent using deallocated memory.
606 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
607 R->Destroy(*this);
608
Ted Kremenek076baeb2010-06-08 23:00:58 +0000609 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
610 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
611 // Increment in loop to prevent using deallocated memory.
612 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
613 R->Destroy(*this);
614 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000615
616 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
617 AEnd = DeclAttrs.end();
618 A != AEnd; ++A)
619 A->second->~AttrVec();
620}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000621
Douglas Gregor1a809332010-05-23 18:26:36 +0000622void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
623 Deallocations.push_back(std::make_pair(Callback, Data));
624}
625
Mike Stump11289f42009-09-09 15:08:12 +0000626void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000627ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000628 ExternalSource.reset(Source.take());
629}
630
Chris Lattner4eb445d2007-01-26 01:27:23 +0000631void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000632 llvm::errs() << "\n*** AST Context Stats:\n";
633 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000634
Douglas Gregora30d0462009-05-26 14:40:08 +0000635 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000636#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000637#define ABSTRACT_TYPE(Name, Parent)
638#include "clang/AST/TypeNodes.def"
639 0 // Extra
640 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000641
Chris Lattner4eb445d2007-01-26 01:27:23 +0000642 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
643 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000644 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000645 }
646
Douglas Gregora30d0462009-05-26 14:40:08 +0000647 unsigned Idx = 0;
648 unsigned TotalBytes = 0;
649#define TYPE(Name, Parent) \
650 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000651 llvm::errs() << " " << counts[Idx] << " " << #Name \
652 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000653 TotalBytes += counts[Idx] * sizeof(Name##Type); \
654 ++Idx;
655#define ABSTRACT_TYPE(Name, Parent)
656#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000657
Chandler Carruth3c147a72011-07-04 05:32:14 +0000658 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
659
Douglas Gregor7454c562010-07-02 20:37:36 +0000660 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000661 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
662 << NumImplicitDefaultConstructors
663 << " implicit default constructors created\n";
664 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
665 << NumImplicitCopyConstructors
666 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000667 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000668 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
669 << NumImplicitMoveConstructors
670 << " implicit move constructors created\n";
671 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
672 << NumImplicitCopyAssignmentOperators
673 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000674 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000675 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
676 << NumImplicitMoveAssignmentOperators
677 << " implicit move assignment operators created\n";
678 llvm::errs() << NumImplicitDestructorsDeclared << "/"
679 << NumImplicitDestructors
680 << " implicit destructors created\n";
681
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000682 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000683 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000684 ExternalSource->PrintStats();
685 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000686
Douglas Gregor5b11d492010-07-25 17:53:33 +0000687 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000688}
689
Douglas Gregor801c99d2011-08-12 06:49:56 +0000690TypedefDecl *ASTContext::getInt128Decl() const {
691 if (!Int128Decl) {
692 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
693 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
694 getTranslationUnitDecl(),
695 SourceLocation(),
696 SourceLocation(),
697 &Idents.get("__int128_t"),
698 TInfo);
699 }
700
701 return Int128Decl;
702}
703
704TypedefDecl *ASTContext::getUInt128Decl() const {
705 if (!UInt128Decl) {
706 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
707 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
708 getTranslationUnitDecl(),
709 SourceLocation(),
710 SourceLocation(),
711 &Idents.get("__uint128_t"),
712 TInfo);
713 }
714
715 return UInt128Decl;
716}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000717
John McCall48f2d582009-10-23 23:03:21 +0000718void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000719 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000720 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000721 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000722}
723
Douglas Gregore8bbc122011-09-02 00:18:52 +0000724void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
725 assert((!this->Target || this->Target == &Target) &&
726 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000727 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000728
Douglas Gregore8bbc122011-09-02 00:18:52 +0000729 this->Target = &Target;
730
731 ABI.reset(createCXXABI(Target));
732 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
733
Chris Lattner970e54e2006-11-12 00:37:36 +0000734 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000735 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chris Lattner970e54e2006-11-12 00:37:36 +0000737 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000738 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000739 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000740 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000741 InitBuiltinType(CharTy, BuiltinType::Char_S);
742 else
743 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000744 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000745 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
746 InitBuiltinType(ShortTy, BuiltinType::Short);
747 InitBuiltinType(IntTy, BuiltinType::Int);
748 InitBuiltinType(LongTy, BuiltinType::Long);
749 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattner970e54e2006-11-12 00:37:36 +0000751 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000752 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
753 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
754 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
755 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
756 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000757
Chris Lattner970e54e2006-11-12 00:37:36 +0000758 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000759 InitBuiltinType(FloatTy, BuiltinType::Float);
760 InitBuiltinType(DoubleTy, BuiltinType::Double);
761 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000762
Chris Lattnerf122cef2009-04-30 02:43:43 +0000763 // GNU extension, 128-bit integers.
764 InitBuiltinType(Int128Ty, BuiltinType::Int128);
765 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
766
Abramo Bagnara06782942012-09-09 10:13:32 +0000767 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000768 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000769 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
770 else // -fshort-wchar makes wchar_t be unsigned.
771 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000772 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000773 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000774
James Molloy36365542012-05-04 10:55:22 +0000775 WIntTy = getFromTargetType(Target.getWIntType());
776
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000777 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
778 InitBuiltinType(Char16Ty, BuiltinType::Char16);
779 else // C99
780 Char16Ty = getFromTargetType(Target.getChar16Type());
781
782 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
783 InitBuiltinType(Char32Ty, BuiltinType::Char32);
784 else // C99
785 Char32Ty = getFromTargetType(Target.getChar32Type());
786
Douglas Gregor4619e432008-12-05 23:32:09 +0000787 // Placeholder type for type-dependent expressions whose type is
788 // completely unknown. No code should ever check a type against
789 // DependentTy and users should never see it; however, it is here to
790 // help diagnose failures to properly check for type-dependent
791 // expressions.
792 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000793
John McCall36e7fe32010-10-12 00:20:44 +0000794 // Placeholder type for functions.
795 InitBuiltinType(OverloadTy, BuiltinType::Overload);
796
John McCall0009fcc2011-04-26 20:42:42 +0000797 // Placeholder type for bound members.
798 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
799
John McCall526ab472011-10-25 17:37:35 +0000800 // Placeholder type for pseudo-objects.
801 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
802
John McCall31996342011-04-07 08:22:57 +0000803 // "any" type; useful for debugger-like clients.
804 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
805
John McCall8a6b59a2011-10-17 18:09:15 +0000806 // Placeholder type for unbridged ARC casts.
807 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
808
Eli Friedman34866c72012-08-31 00:14:07 +0000809 // Placeholder type for builtin functions.
810 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
811
Chris Lattner970e54e2006-11-12 00:37:36 +0000812 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000813 FloatComplexTy = getComplexType(FloatTy);
814 DoubleComplexTy = getComplexType(DoubleTy);
815 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000817 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000818 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
819 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000820 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000821
822 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000823 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
824 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000825
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000826 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000827
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000828 // void * type
829 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000830
831 // nullptr type (C++0x 2.14.7)
832 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000833
834 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
835 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000836
837 // Builtin type used to help define __builtin_va_list.
838 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000839}
840
David Blaikie9c902b52011-09-25 23:23:43 +0000841DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000842 return SourceMgr.getDiagnostics();
843}
844
Douglas Gregor561eceb2010-08-30 16:49:28 +0000845AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
846 AttrVec *&Result = DeclAttrs[D];
847 if (!Result) {
848 void *Mem = Allocate(sizeof(AttrVec));
849 Result = new (Mem) AttrVec;
850 }
851
852 return *Result;
853}
854
855/// \brief Erase the attributes corresponding to the given declaration.
856void ASTContext::eraseDeclAttrs(const Decl *D) {
857 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
858 if (Pos != DeclAttrs.end()) {
859 Pos->second->~AttrVec();
860 DeclAttrs.erase(Pos);
861 }
862}
863
Douglas Gregor86d142a2009-10-08 07:24:58 +0000864MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000865ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000866 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000867 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000868 = InstantiatedFromStaticDataMember.find(Var);
869 if (Pos == InstantiatedFromStaticDataMember.end())
870 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000871
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000872 return Pos->second;
873}
874
Mike Stump11289f42009-09-09 15:08:12 +0000875void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000876ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000877 TemplateSpecializationKind TSK,
878 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000879 assert(Inst->isStaticDataMember() && "Not a static data member");
880 assert(Tmpl->isStaticDataMember() && "Not a static data member");
881 assert(!InstantiatedFromStaticDataMember[Inst] &&
882 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000883 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000884 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000885}
886
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000887FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
888 const FunctionDecl *FD){
889 assert(FD && "Specialization is 0");
890 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000891 = ClassScopeSpecializationPattern.find(FD);
892 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000893 return 0;
894
895 return Pos->second;
896}
897
898void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
899 FunctionDecl *Pattern) {
900 assert(FD && "Specialization is 0");
901 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000902 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000903}
904
John McCalle61f2ba2009-11-18 02:36:19 +0000905NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000906ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000907 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000908 = InstantiatedFromUsingDecl.find(UUD);
909 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000910 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000911
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000912 return Pos->second;
913}
914
915void
John McCallb96ec562009-12-04 22:46:56 +0000916ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
917 assert((isa<UsingDecl>(Pattern) ||
918 isa<UnresolvedUsingValueDecl>(Pattern) ||
919 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
920 "pattern decl is not a using decl");
921 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
922 InstantiatedFromUsingDecl[Inst] = Pattern;
923}
924
925UsingShadowDecl *
926ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
927 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
928 = InstantiatedFromUsingShadowDecl.find(Inst);
929 if (Pos == InstantiatedFromUsingShadowDecl.end())
930 return 0;
931
932 return Pos->second;
933}
934
935void
936ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
937 UsingShadowDecl *Pattern) {
938 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
939 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000940}
941
Anders Carlsson5da84842009-09-01 04:26:58 +0000942FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
943 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
944 = InstantiatedFromUnnamedFieldDecl.find(Field);
945 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
946 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000947
Anders Carlsson5da84842009-09-01 04:26:58 +0000948 return Pos->second;
949}
950
951void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
952 FieldDecl *Tmpl) {
953 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
954 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
955 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
956 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000957
Anders Carlsson5da84842009-09-01 04:26:58 +0000958 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
959}
960
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000961bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
962 const FieldDecl *LastFD) const {
963 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000964 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000965}
966
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000967bool ASTContext::ZeroBitfieldFollowsBitfield(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) == 0 &&
971 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000972}
973
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000974bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
975 const FieldDecl *LastFD) const {
976 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000977 FD->getBitWidthValue(*this) &&
978 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000979}
980
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000981bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000982 const FieldDecl *LastFD) const {
983 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000984 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000985}
986
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000987bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000988 const FieldDecl *LastFD) const {
989 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000990 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000991}
992
Douglas Gregor832940b2010-03-02 23:58:15 +0000993ASTContext::overridden_cxx_method_iterator
994ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
995 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
996 = OverriddenMethods.find(Method);
997 if (Pos == OverriddenMethods.end())
998 return 0;
999
1000 return Pos->second.begin();
1001}
1002
1003ASTContext::overridden_cxx_method_iterator
1004ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1005 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1006 = OverriddenMethods.find(Method);
1007 if (Pos == OverriddenMethods.end())
1008 return 0;
1009
1010 return Pos->second.end();
1011}
1012
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001013unsigned
1014ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1015 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1016 = OverriddenMethods.find(Method);
1017 if (Pos == OverriddenMethods.end())
1018 return 0;
1019
1020 return Pos->second.size();
1021}
1022
Douglas Gregor832940b2010-03-02 23:58:15 +00001023void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1024 const CXXMethodDecl *Overridden) {
1025 OverriddenMethods[Method].push_back(Overridden);
1026}
1027
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001028void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1029 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1030 assert(!Import->isFromASTFile() && "Non-local import declaration");
1031 if (!FirstLocalImport) {
1032 FirstLocalImport = Import;
1033 LastLocalImport = Import;
1034 return;
1035 }
1036
1037 LastLocalImport->NextLocalImport = Import;
1038 LastLocalImport = Import;
1039}
1040
Chris Lattner53cfe802007-07-18 17:52:12 +00001041//===----------------------------------------------------------------------===//
1042// Type Sizing and Analysis
1043//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001044
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001045/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1046/// scalar floating point type.
1047const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001048 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001049 assert(BT && "Not a floating point type!");
1050 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001051 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001052 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001053 case BuiltinType::Float: return Target->getFloatFormat();
1054 case BuiltinType::Double: return Target->getDoubleFormat();
1055 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001056 }
1057}
1058
Ken Dyck160146e2010-01-27 17:10:57 +00001059/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001060/// specified decl. Note that bitfields do not have a valid alignment, so
1061/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001062/// If @p RefAsPointee, references are treated like their underlying type
1063/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001064CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001065 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001066
John McCall94268702010-10-08 18:24:19 +00001067 bool UseAlignAttrOnly = false;
1068 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1069 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001070
John McCall94268702010-10-08 18:24:19 +00001071 // __attribute__((aligned)) can increase or decrease alignment
1072 // *except* on a struct or struct member, where it only increases
1073 // alignment unless 'packed' is also specified.
1074 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001075 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001076 // ignore that possibility; Sema should diagnose it.
1077 if (isa<FieldDecl>(D)) {
1078 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1079 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1080 } else {
1081 UseAlignAttrOnly = true;
1082 }
1083 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001084 else if (isa<FieldDecl>(D))
1085 UseAlignAttrOnly =
1086 D->hasAttr<PackedAttr>() ||
1087 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001088
John McCall4e819612011-01-20 07:57:12 +00001089 // If we're using the align attribute only, just ignore everything
1090 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001091 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001092 // do nothing
1093
John McCall94268702010-10-08 18:24:19 +00001094 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001095 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001096 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001097 if (RefAsPointee)
1098 T = RT->getPointeeType();
1099 else
1100 T = getPointerType(RT->getPointeeType());
1101 }
1102 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001103 // Adjust alignments of declarations with array type by the
1104 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001105 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001106 const ArrayType *arrayType;
1107 if (MinWidth && (arrayType = getAsArrayType(T))) {
1108 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001109 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001110 else if (isa<ConstantArrayType>(arrayType) &&
1111 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001112 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001113
John McCall33ddac02011-01-19 10:06:00 +00001114 // Walk through any array types while we're at it.
1115 T = getBaseElementType(arrayType);
1116 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001117 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001118 }
John McCall4e819612011-01-20 07:57:12 +00001119
1120 // Fields can be subject to extra alignment constraints, like if
1121 // the field is packed, the struct is packed, or the struct has a
1122 // a max-field-alignment constraint (#pragma pack). So calculate
1123 // the actual alignment of the field within the struct, and then
1124 // (as we're expected to) constrain that by the alignment of the type.
1125 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1126 // So calculate the alignment of the field.
1127 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1128
1129 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001130 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001131
1132 // Use the GCD of that and the offset within the record.
1133 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1134 if (offset > 0) {
1135 // Alignment is always a power of 2, so the GCD will be a power of 2,
1136 // which means we get to do this crazy thing instead of Euclid's.
1137 uint64_t lowBitOfOffset = offset & (~offset + 1);
1138 if (lowBitOfOffset < fieldAlign)
1139 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1140 }
1141
1142 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001143 }
Chris Lattner68061312009-01-24 21:53:27 +00001144 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001145
Ken Dyckcc56c542011-01-15 18:38:59 +00001146 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001147}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001148
John McCallf1249922012-08-21 04:10:00 +00001149// getTypeInfoDataSizeInChars - Return the size of a type, in
1150// chars. If the type is a record, its data size is returned. This is
1151// the size of the memcpy that's performed when assigning this type
1152// using a trivial copy/move assignment operator.
1153std::pair<CharUnits, CharUnits>
1154ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1155 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1156
1157 // In C++, objects can sometimes be allocated into the tail padding
1158 // of a base-class subobject. We decide whether that's possible
1159 // during class layout, so here we can just trust the layout results.
1160 if (getLangOpts().CPlusPlus) {
1161 if (const RecordType *RT = T->getAs<RecordType>()) {
1162 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1163 sizeAndAlign.first = layout.getDataSize();
1164 }
1165 }
1166
1167 return sizeAndAlign;
1168}
1169
John McCall87fe5d52010-05-20 01:18:31 +00001170std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001171ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001172 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001173 return std::make_pair(toCharUnitsFromBits(Info.first),
1174 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001175}
1176
1177std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001178ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001179 return getTypeInfoInChars(T.getTypePtr());
1180}
1181
Daniel Dunbarc6475872012-03-09 04:12:54 +00001182std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1183 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1184 if (it != MemoizedTypeInfo.end())
1185 return it->second;
1186
1187 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1188 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1189 return Info;
1190}
1191
1192/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1193/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001194///
1195/// FIXME: Pointers into different addr spaces could have different sizes and
1196/// alignment requirements: getPointerInfo should take an AddrSpace, this
1197/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001198std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001199ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001200 uint64_t Width=0;
1201 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001202 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001203#define TYPE(Class, Base)
1204#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001205#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001206#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1207#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001208 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001209
Chris Lattner355332d2007-07-13 22:27:08 +00001210 case Type::FunctionNoProto:
1211 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001212 // GCC extension: alignof(function) = 32 bits
1213 Width = 0;
1214 Align = 32;
1215 break;
1216
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001217 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001218 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001219 Width = 0;
1220 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1221 break;
1222
Steve Naroff5c131802007-08-30 01:06:46 +00001223 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001224 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001225
Chris Lattner37e05872008-03-05 18:54:05 +00001226 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001227 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001228 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1229 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001230 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001231 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001232 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001233 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001234 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001235 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001236 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001237 const VectorType *VT = cast<VectorType>(T);
1238 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1239 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001240 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001241 // If the alignment is not a power of 2, round up to the next power of 2.
1242 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001243 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001244 Align = llvm::NextPowerOf2(Align);
1245 Width = llvm::RoundUpToAlignment(Width, Align);
1246 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001247 // Adjust the alignment based on the target max.
1248 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1249 if (TargetVectorAlign && TargetVectorAlign < Align)
1250 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001251 break;
1252 }
Chris Lattner647fb222007-07-18 18:26:58 +00001253
Chris Lattner7570e9c2008-03-08 08:52:55 +00001254 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001255 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001256 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001257 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001258 // GCC extension: alignof(void) = 8 bits.
1259 Width = 0;
1260 Align = 8;
1261 break;
1262
Chris Lattner6a4f7452007-12-19 19:23:28 +00001263 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001264 Width = Target->getBoolWidth();
1265 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001266 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001267 case BuiltinType::Char_S:
1268 case BuiltinType::Char_U:
1269 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001270 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001271 Width = Target->getCharWidth();
1272 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001273 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001274 case BuiltinType::WChar_S:
1275 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001276 Width = Target->getWCharWidth();
1277 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001278 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001279 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001280 Width = Target->getChar16Width();
1281 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001282 break;
1283 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001284 Width = Target->getChar32Width();
1285 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001286 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001287 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001288 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001289 Width = Target->getShortWidth();
1290 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001291 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001292 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001293 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001294 Width = Target->getIntWidth();
1295 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001296 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001297 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001298 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001299 Width = Target->getLongWidth();
1300 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001301 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001302 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001303 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001304 Width = Target->getLongLongWidth();
1305 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001306 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001307 case BuiltinType::Int128:
1308 case BuiltinType::UInt128:
1309 Width = 128;
1310 Align = 128; // int128_t is 128-bit aligned on all targets.
1311 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001312 case BuiltinType::Half:
1313 Width = Target->getHalfWidth();
1314 Align = Target->getHalfAlign();
1315 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001316 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001317 Width = Target->getFloatWidth();
1318 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001319 break;
1320 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001321 Width = Target->getDoubleWidth();
1322 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001323 break;
1324 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001325 Width = Target->getLongDoubleWidth();
1326 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001327 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001328 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001329 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1330 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001331 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001332 case BuiltinType::ObjCId:
1333 case BuiltinType::ObjCClass:
1334 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001335 Width = Target->getPointerWidth(0);
1336 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001337 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001338 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001339 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001340 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001341 Width = Target->getPointerWidth(0);
1342 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001343 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001344 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001345 unsigned AS = getTargetAddressSpace(
1346 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001347 Width = Target->getPointerWidth(AS);
1348 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001349 break;
1350 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001351 case Type::LValueReference:
1352 case Type::RValueReference: {
1353 // alignof and sizeof should never enter this code path here, so we go
1354 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001355 unsigned AS = getTargetAddressSpace(
1356 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001357 Width = Target->getPointerWidth(AS);
1358 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001359 break;
1360 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001361 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001362 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001363 Width = Target->getPointerWidth(AS);
1364 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001365 break;
1366 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001367 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001368 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001369 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001370 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001371 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001372 Align = PtrDiffInfo.second;
1373 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001374 }
Chris Lattner647fb222007-07-18 18:26:58 +00001375 case Type::Complex: {
1376 // Complex types have the same alignment as their elements, but twice the
1377 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001378 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001379 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001380 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001381 Align = EltInfo.second;
1382 break;
1383 }
John McCall8b07ec22010-05-15 11:32:37 +00001384 case Type::ObjCObject:
1385 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001386 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001387 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001388 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001389 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001390 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001391 break;
1392 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001393 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001394 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001395 const TagType *TT = cast<TagType>(T);
1396
1397 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001398 Width = 8;
1399 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001400 break;
1401 }
Mike Stump11289f42009-09-09 15:08:12 +00001402
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001403 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001404 return getTypeInfo(ET->getDecl()->getIntegerType());
1405
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001406 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001407 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001408 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001409 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001410 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001411 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001412
Chris Lattner63d2b362009-10-22 05:17:15 +00001413 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001414 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1415 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001416
Richard Smith30482bc2011-02-20 03:19:35 +00001417 case Type::Auto: {
1418 const AutoType *A = cast<AutoType>(T);
1419 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001420 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001421 }
1422
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001423 case Type::Paren:
1424 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1425
Douglas Gregoref462e62009-04-30 17:32:17 +00001426 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001427 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001428 std::pair<uint64_t, unsigned> Info
1429 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001430 // If the typedef has an aligned attribute on it, it overrides any computed
1431 // alignment we have. This violates the GCC documentation (which says that
1432 // attribute(aligned) can only round up) but matches its implementation.
1433 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1434 Align = AttrAlign;
1435 else
1436 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001437 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001438 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001439 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001440
1441 case Type::TypeOfExpr:
1442 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1443 .getTypePtr());
1444
1445 case Type::TypeOf:
1446 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1447
Anders Carlsson81df7b82009-06-24 19:06:50 +00001448 case Type::Decltype:
1449 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1450 .getTypePtr());
1451
Alexis Hunte852b102011-05-24 22:41:36 +00001452 case Type::UnaryTransform:
1453 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1454
Abramo Bagnara6150c882010-05-11 21:36:43 +00001455 case Type::Elaborated:
1456 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001457
John McCall81904512011-01-06 01:58:22 +00001458 case Type::Attributed:
1459 return getTypeInfo(
1460 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1461
Richard Smith3f1b5d02011-05-05 21:57:07 +00001462 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001463 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001464 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001465 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1466 // A type alias template specialization may refer to a typedef with the
1467 // aligned attribute on it.
1468 if (TST->isTypeAlias())
1469 return getTypeInfo(TST->getAliasedType().getTypePtr());
1470 else
1471 return getTypeInfo(getCanonicalType(T));
1472 }
1473
Eli Friedman0dfb8892011-10-06 23:00:33 +00001474 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001475 std::pair<uint64_t, unsigned> Info
1476 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1477 Width = Info.first;
1478 Align = Info.second;
1479 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1480 llvm::isPowerOf2_64(Width)) {
1481 // We can potentially perform lock-free atomic operations for this
1482 // type; promote the alignment appropriately.
1483 // FIXME: We could potentially promote the width here as well...
1484 // is that worthwhile? (Non-struct atomic types generally have
1485 // power-of-two size anyway, but structs might not. Requires a bit
1486 // of implementation work to make sure we zero out the extra bits.)
1487 Align = static_cast<unsigned>(Width);
1488 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001489 }
1490
Douglas Gregoref462e62009-04-30 17:32:17 +00001491 }
Mike Stump11289f42009-09-09 15:08:12 +00001492
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001493 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001494 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001495}
1496
Ken Dyckcc56c542011-01-15 18:38:59 +00001497/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1498CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1499 return CharUnits::fromQuantity(BitSize / getCharWidth());
1500}
1501
Ken Dyckb0fcc592011-02-11 01:54:29 +00001502/// toBits - Convert a size in characters to a size in characters.
1503int64_t ASTContext::toBits(CharUnits CharSize) const {
1504 return CharSize.getQuantity() * getCharWidth();
1505}
1506
Ken Dyck8c89d592009-12-22 14:23:30 +00001507/// getTypeSizeInChars - Return the size of the specified type, in characters.
1508/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001509CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001510 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001511}
Jay Foad39c79802011-01-12 09:06:06 +00001512CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001513 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001514}
1515
Ken Dycka6046ab2010-01-26 17:25:18 +00001516/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001517/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001518CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001519 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001520}
Jay Foad39c79802011-01-12 09:06:06 +00001521CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001522 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001523}
1524
Chris Lattnera3402cd2009-01-27 18:08:34 +00001525/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1526/// type for the current target in bits. This can be different than the ABI
1527/// alignment in cases where it is beneficial for performance to overalign
1528/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001529unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001530 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001531
1532 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001533 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001534 T = CT->getElementType().getTypePtr();
1535 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001536 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1537 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001538 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1539
Chris Lattnera3402cd2009-01-27 18:08:34 +00001540 return ABIAlign;
1541}
1542
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001543/// DeepCollectObjCIvars -
1544/// This routine first collects all declared, but not synthesized, ivars in
1545/// super class and then collects all ivars, including those synthesized for
1546/// current class. This routine is used for implementation of current class
1547/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001548///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001549void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1550 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001551 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001552 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1553 DeepCollectObjCIvars(SuperClass, false, Ivars);
1554 if (!leafClass) {
1555 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1556 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001557 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001558 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001559 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001560 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001561 Iv= Iv->getNextIvar())
1562 Ivars.push_back(Iv);
1563 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001564}
1565
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001566/// CollectInheritedProtocols - Collect all protocols in current class and
1567/// those inherited by it.
1568void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001569 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001570 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001571 // We can use protocol_iterator here instead of
1572 // all_referenced_protocol_iterator since we are walking all categories.
1573 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1574 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001575 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001576 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001577 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001578 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001579 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001580 CollectInheritedProtocols(*P, Protocols);
1581 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001582 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001583
1584 // Categories of this Interface.
1585 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1586 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1587 CollectInheritedProtocols(CDeclChain, Protocols);
1588 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1589 while (SD) {
1590 CollectInheritedProtocols(SD, Protocols);
1591 SD = SD->getSuperClass();
1592 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001593 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001594 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001595 PE = OC->protocol_end(); P != PE; ++P) {
1596 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001597 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001598 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1599 PE = Proto->protocol_end(); P != PE; ++P)
1600 CollectInheritedProtocols(*P, Protocols);
1601 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001602 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001603 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1604 PE = OP->protocol_end(); P != PE; ++P) {
1605 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001606 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001607 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1608 PE = Proto->protocol_end(); P != PE; ++P)
1609 CollectInheritedProtocols(*P, Protocols);
1610 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001611 }
1612}
1613
Jay Foad39c79802011-01-12 09:06:06 +00001614unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001615 unsigned count = 0;
1616 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001617 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1618 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001619 count += CDecl->ivar_size();
1620
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001621 // Count ivar defined in this class's implementation. This
1622 // includes synthesized ivars.
1623 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001624 count += ImplDecl->ivar_size();
1625
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001626 return count;
1627}
1628
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001629bool ASTContext::isSentinelNullExpr(const Expr *E) {
1630 if (!E)
1631 return false;
1632
1633 // nullptr_t is always treated as null.
1634 if (E->getType()->isNullPtrType()) return true;
1635
1636 if (E->getType()->isAnyPointerType() &&
1637 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1638 Expr::NPC_ValueDependentIsNull))
1639 return true;
1640
1641 // Unfortunately, __null has type 'int'.
1642 if (isa<GNUNullExpr>(E)) return true;
1643
1644 return false;
1645}
1646
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001647/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1648ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1649 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1650 I = ObjCImpls.find(D);
1651 if (I != ObjCImpls.end())
1652 return cast<ObjCImplementationDecl>(I->second);
1653 return 0;
1654}
1655/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1656ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1657 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1658 I = ObjCImpls.find(D);
1659 if (I != ObjCImpls.end())
1660 return cast<ObjCCategoryImplDecl>(I->second);
1661 return 0;
1662}
1663
1664/// \brief Set the implementation of ObjCInterfaceDecl.
1665void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1666 ObjCImplementationDecl *ImplD) {
1667 assert(IFaceD && ImplD && "Passed null params");
1668 ObjCImpls[IFaceD] = ImplD;
1669}
1670/// \brief Set the implementation of ObjCCategoryDecl.
1671void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1672 ObjCCategoryImplDecl *ImplD) {
1673 assert(CatD && ImplD && "Passed null params");
1674 ObjCImpls[CatD] = ImplD;
1675}
1676
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001677ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1678 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1679 return ID;
1680 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1681 return CD->getClassInterface();
1682 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1683 return IMD->getClassInterface();
1684
1685 return 0;
1686}
1687
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001688/// \brief Get the copy initialization expression of VarDecl,or NULL if
1689/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001690Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001691 assert(VD && "Passed null params");
1692 assert(VD->hasAttr<BlocksAttr>() &&
1693 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001694 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001695 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001696 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1697}
1698
1699/// \brief Set the copy inialization expression of a block var decl.
1700void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1701 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001702 assert(VD->hasAttr<BlocksAttr>() &&
1703 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001704 BlockVarCopyInits[VD] = Init;
1705}
1706
John McCallbcd03502009-12-07 02:54:59 +00001707TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001708 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001709 if (!DataSize)
1710 DataSize = TypeLoc::getFullDataSizeForType(T);
1711 else
1712 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001713 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001714
John McCallbcd03502009-12-07 02:54:59 +00001715 TypeSourceInfo *TInfo =
1716 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1717 new (TInfo) TypeSourceInfo(T);
1718 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001719}
1720
John McCallbcd03502009-12-07 02:54:59 +00001721TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001722 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001723 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001724 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001725 return DI;
1726}
1727
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001728const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001729ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001730 return getObjCLayout(D, 0);
1731}
1732
1733const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001734ASTContext::getASTObjCImplementationLayout(
1735 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001736 return getObjCLayout(D->getClassInterface(), D);
1737}
1738
Chris Lattner983a8bb2007-07-13 22:13:22 +00001739//===----------------------------------------------------------------------===//
1740// Type creation/memoization methods
1741//===----------------------------------------------------------------------===//
1742
Jay Foad39c79802011-01-12 09:06:06 +00001743QualType
John McCall33ddac02011-01-19 10:06:00 +00001744ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1745 unsigned fastQuals = quals.getFastQualifiers();
1746 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001747
1748 // Check if we've already instantiated this type.
1749 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001750 ExtQuals::Profile(ID, baseType, quals);
1751 void *insertPos = 0;
1752 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1753 assert(eq->getQualifiers() == quals);
1754 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001755 }
1756
John McCall33ddac02011-01-19 10:06:00 +00001757 // If the base type is not canonical, make the appropriate canonical type.
1758 QualType canon;
1759 if (!baseType->isCanonicalUnqualified()) {
1760 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001761 canonSplit.Quals.addConsistentQualifiers(quals);
1762 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001763
1764 // Re-find the insert position.
1765 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1766 }
1767
1768 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1769 ExtQualNodes.InsertNode(eq, insertPos);
1770 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001771}
1772
Jay Foad39c79802011-01-12 09:06:06 +00001773QualType
1774ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001775 QualType CanT = getCanonicalType(T);
1776 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001777 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001778
John McCall8ccfcb52009-09-24 19:53:00 +00001779 // If we are composing extended qualifiers together, merge together
1780 // into one ExtQuals node.
1781 QualifierCollector Quals;
1782 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001783
John McCall8ccfcb52009-09-24 19:53:00 +00001784 // If this type already has an address space specified, it cannot get
1785 // another one.
1786 assert(!Quals.hasAddressSpace() &&
1787 "Type cannot be in multiple addr spaces!");
1788 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001789
John McCall8ccfcb52009-09-24 19:53:00 +00001790 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001791}
1792
Chris Lattnerd60183d2009-02-18 22:53:11 +00001793QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001794 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001795 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001796 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001797 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001798
John McCall53fa7142010-12-24 02:08:15 +00001799 if (const PointerType *ptr = T->getAs<PointerType>()) {
1800 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001801 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001802 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1803 return getPointerType(ResultType);
1804 }
1805 }
Mike Stump11289f42009-09-09 15:08:12 +00001806
John McCall8ccfcb52009-09-24 19:53:00 +00001807 // If we are composing extended qualifiers together, merge together
1808 // into one ExtQuals node.
1809 QualifierCollector Quals;
1810 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001811
John McCall8ccfcb52009-09-24 19:53:00 +00001812 // If this type already has an ObjCGC specified, it cannot get
1813 // another one.
1814 assert(!Quals.hasObjCGCAttr() &&
1815 "Type cannot have multiple ObjCGCs!");
1816 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001817
John McCall8ccfcb52009-09-24 19:53:00 +00001818 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001819}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001820
John McCall4f5019e2010-12-19 02:44:49 +00001821const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1822 FunctionType::ExtInfo Info) {
1823 if (T->getExtInfo() == Info)
1824 return T;
1825
1826 QualType Result;
1827 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1828 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1829 } else {
1830 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1831 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1832 EPI.ExtInfo = Info;
1833 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1834 FPT->getNumArgs(), EPI);
1835 }
1836
1837 return cast<FunctionType>(Result.getTypePtr());
1838}
1839
Chris Lattnerc6395932007-06-22 20:56:16 +00001840/// getComplexType - Return the uniqued reference to the type for a complex
1841/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001842QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001843 // Unique pointers, to guarantee there is only one pointer of a particular
1844 // structure.
1845 llvm::FoldingSetNodeID ID;
1846 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001847
Chris Lattnerc6395932007-06-22 20:56:16 +00001848 void *InsertPos = 0;
1849 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1850 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001851
Chris Lattnerc6395932007-06-22 20:56:16 +00001852 // If the pointee type isn't canonical, this won't be a canonical type either,
1853 // so fill in the canonical type field.
1854 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001855 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001856 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001857
Chris Lattnerc6395932007-06-22 20:56:16 +00001858 // Get the new insert position for the node we care about.
1859 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001860 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001861 }
John McCall90d1c2d2009-09-24 23:30:46 +00001862 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001863 Types.push_back(New);
1864 ComplexTypes.InsertNode(New, InsertPos);
1865 return QualType(New, 0);
1866}
1867
Chris Lattner970e54e2006-11-12 00:37:36 +00001868/// getPointerType - Return the uniqued reference to the type for a pointer to
1869/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001870QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001871 // Unique pointers, to guarantee there is only one pointer of a particular
1872 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001873 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001874 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001875
Chris Lattner67521df2007-01-27 01:29:36 +00001876 void *InsertPos = 0;
1877 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001878 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001879
Chris Lattner7ccecb92006-11-12 08:50:50 +00001880 // If the pointee type isn't canonical, this won't be a canonical type either,
1881 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001882 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001883 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001884 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001885
Chris Lattner67521df2007-01-27 01:29:36 +00001886 // Get the new insert position for the node we care about.
1887 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001888 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001889 }
John McCall90d1c2d2009-09-24 23:30:46 +00001890 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001891 Types.push_back(New);
1892 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001893 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001894}
1895
Mike Stump11289f42009-09-09 15:08:12 +00001896/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001897/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001898QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001899 assert(T->isFunctionType() && "block of function types only");
1900 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001901 // structure.
1902 llvm::FoldingSetNodeID ID;
1903 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001904
Steve Naroffec33ed92008-08-27 16:04:49 +00001905 void *InsertPos = 0;
1906 if (BlockPointerType *PT =
1907 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1908 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001909
1910 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001911 // type either so fill in the canonical type field.
1912 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001913 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001914 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001915
Steve Naroffec33ed92008-08-27 16:04:49 +00001916 // Get the new insert position for the node we care about.
1917 BlockPointerType *NewIP =
1918 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001919 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001920 }
John McCall90d1c2d2009-09-24 23:30:46 +00001921 BlockPointerType *New
1922 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001923 Types.push_back(New);
1924 BlockPointerTypes.InsertNode(New, InsertPos);
1925 return QualType(New, 0);
1926}
1927
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001928/// getLValueReferenceType - Return the uniqued reference to the type for an
1929/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001930QualType
1931ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001932 assert(getCanonicalType(T) != OverloadTy &&
1933 "Unresolved overloaded function type");
1934
Bill Wendling3708c182007-05-27 10:15:43 +00001935 // Unique pointers, to guarantee there is only one pointer of a particular
1936 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001937 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001938 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001939
1940 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001941 if (LValueReferenceType *RT =
1942 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001943 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001944
John McCallfc93cf92009-10-22 22:37:11 +00001945 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1946
Bill Wendling3708c182007-05-27 10:15:43 +00001947 // If the referencee type isn't canonical, this won't be a canonical type
1948 // either, so fill in the canonical type field.
1949 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001950 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1951 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1952 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001953
Bill Wendling3708c182007-05-27 10:15:43 +00001954 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001955 LValueReferenceType *NewIP =
1956 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001957 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001958 }
1959
John McCall90d1c2d2009-09-24 23:30:46 +00001960 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001961 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1962 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001963 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001964 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001965
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001966 return QualType(New, 0);
1967}
1968
1969/// getRValueReferenceType - Return the uniqued reference to the type for an
1970/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001971QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001972 // Unique pointers, to guarantee there is only one pointer of a particular
1973 // structure.
1974 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001975 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001976
1977 void *InsertPos = 0;
1978 if (RValueReferenceType *RT =
1979 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1980 return QualType(RT, 0);
1981
John McCallfc93cf92009-10-22 22:37:11 +00001982 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1983
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001984 // If the referencee type isn't canonical, this won't be a canonical type
1985 // either, so fill in the canonical type field.
1986 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001987 if (InnerRef || !T.isCanonical()) {
1988 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1989 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001990
1991 // Get the new insert position for the node we care about.
1992 RValueReferenceType *NewIP =
1993 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001994 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001995 }
1996
John McCall90d1c2d2009-09-24 23:30:46 +00001997 RValueReferenceType *New
1998 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001999 Types.push_back(New);
2000 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002001 return QualType(New, 0);
2002}
2003
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002004/// getMemberPointerType - Return the uniqued reference to the type for a
2005/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002006QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002007 // Unique pointers, to guarantee there is only one pointer of a particular
2008 // structure.
2009 llvm::FoldingSetNodeID ID;
2010 MemberPointerType::Profile(ID, T, Cls);
2011
2012 void *InsertPos = 0;
2013 if (MemberPointerType *PT =
2014 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2015 return QualType(PT, 0);
2016
2017 // If the pointee or class type isn't canonical, this won't be a canonical
2018 // type either, so fill in the canonical type field.
2019 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002020 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002021 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2022
2023 // Get the new insert position for the node we care about.
2024 MemberPointerType *NewIP =
2025 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002026 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002027 }
John McCall90d1c2d2009-09-24 23:30:46 +00002028 MemberPointerType *New
2029 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002030 Types.push_back(New);
2031 MemberPointerTypes.InsertNode(New, InsertPos);
2032 return QualType(New, 0);
2033}
2034
Mike Stump11289f42009-09-09 15:08:12 +00002035/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002036/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002037QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002038 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002039 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002040 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002041 assert((EltTy->isDependentType() ||
2042 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002043 "Constant array of VLAs is illegal!");
2044
Chris Lattnere2df3f92009-05-13 04:12:56 +00002045 // Convert the array size into a canonical width matching the pointer size for
2046 // the target.
2047 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002048 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002049 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002050
Chris Lattner23b7eb62007-06-15 23:05:46 +00002051 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002052 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002053
Chris Lattner36f8e652007-01-27 08:31:04 +00002054 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002055 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002056 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002057 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002058
John McCall33ddac02011-01-19 10:06:00 +00002059 // If the element type isn't canonical or has qualifiers, this won't
2060 // be a canonical type either, so fill in the canonical type field.
2061 QualType Canon;
2062 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2063 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002064 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002065 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002066 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002067
Chris Lattner36f8e652007-01-27 08:31:04 +00002068 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002069 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002070 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002071 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002072 }
Mike Stump11289f42009-09-09 15:08:12 +00002073
John McCall90d1c2d2009-09-24 23:30:46 +00002074 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002075 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002076 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002077 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002078 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002079}
2080
John McCall06549462011-01-18 08:40:38 +00002081/// getVariableArrayDecayedType - Turns the given type, which may be
2082/// variably-modified, into the corresponding type with all the known
2083/// sizes replaced with [*].
2084QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2085 // Vastly most common case.
2086 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002087
John McCall06549462011-01-18 08:40:38 +00002088 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002089
John McCall06549462011-01-18 08:40:38 +00002090 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002091 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002092 switch (ty->getTypeClass()) {
2093#define TYPE(Class, Base)
2094#define ABSTRACT_TYPE(Class, Base)
2095#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2096#include "clang/AST/TypeNodes.def"
2097 llvm_unreachable("didn't desugar past all non-canonical types?");
2098
2099 // These types should never be variably-modified.
2100 case Type::Builtin:
2101 case Type::Complex:
2102 case Type::Vector:
2103 case Type::ExtVector:
2104 case Type::DependentSizedExtVector:
2105 case Type::ObjCObject:
2106 case Type::ObjCInterface:
2107 case Type::ObjCObjectPointer:
2108 case Type::Record:
2109 case Type::Enum:
2110 case Type::UnresolvedUsing:
2111 case Type::TypeOfExpr:
2112 case Type::TypeOf:
2113 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002114 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002115 case Type::DependentName:
2116 case Type::InjectedClassName:
2117 case Type::TemplateSpecialization:
2118 case Type::DependentTemplateSpecialization:
2119 case Type::TemplateTypeParm:
2120 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002121 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002122 case Type::PackExpansion:
2123 llvm_unreachable("type should never be variably-modified");
2124
2125 // These types can be variably-modified but should never need to
2126 // further decay.
2127 case Type::FunctionNoProto:
2128 case Type::FunctionProto:
2129 case Type::BlockPointer:
2130 case Type::MemberPointer:
2131 return type;
2132
2133 // These types can be variably-modified. All these modifications
2134 // preserve structure except as noted by comments.
2135 // TODO: if we ever care about optimizing VLAs, there are no-op
2136 // optimizations available here.
2137 case Type::Pointer:
2138 result = getPointerType(getVariableArrayDecayedType(
2139 cast<PointerType>(ty)->getPointeeType()));
2140 break;
2141
2142 case Type::LValueReference: {
2143 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2144 result = getLValueReferenceType(
2145 getVariableArrayDecayedType(lv->getPointeeType()),
2146 lv->isSpelledAsLValue());
2147 break;
2148 }
2149
2150 case Type::RValueReference: {
2151 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2152 result = getRValueReferenceType(
2153 getVariableArrayDecayedType(lv->getPointeeType()));
2154 break;
2155 }
2156
Eli Friedman0dfb8892011-10-06 23:00:33 +00002157 case Type::Atomic: {
2158 const AtomicType *at = cast<AtomicType>(ty);
2159 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2160 break;
2161 }
2162
John McCall06549462011-01-18 08:40:38 +00002163 case Type::ConstantArray: {
2164 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2165 result = getConstantArrayType(
2166 getVariableArrayDecayedType(cat->getElementType()),
2167 cat->getSize(),
2168 cat->getSizeModifier(),
2169 cat->getIndexTypeCVRQualifiers());
2170 break;
2171 }
2172
2173 case Type::DependentSizedArray: {
2174 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2175 result = getDependentSizedArrayType(
2176 getVariableArrayDecayedType(dat->getElementType()),
2177 dat->getSizeExpr(),
2178 dat->getSizeModifier(),
2179 dat->getIndexTypeCVRQualifiers(),
2180 dat->getBracketsRange());
2181 break;
2182 }
2183
2184 // Turn incomplete types into [*] types.
2185 case Type::IncompleteArray: {
2186 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2187 result = getVariableArrayType(
2188 getVariableArrayDecayedType(iat->getElementType()),
2189 /*size*/ 0,
2190 ArrayType::Normal,
2191 iat->getIndexTypeCVRQualifiers(),
2192 SourceRange());
2193 break;
2194 }
2195
2196 // Turn VLA types into [*] types.
2197 case Type::VariableArray: {
2198 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2199 result = getVariableArrayType(
2200 getVariableArrayDecayedType(vat->getElementType()),
2201 /*size*/ 0,
2202 ArrayType::Star,
2203 vat->getIndexTypeCVRQualifiers(),
2204 vat->getBracketsRange());
2205 break;
2206 }
2207 }
2208
2209 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002210 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002211}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002212
Steve Naroffcadebd02007-08-30 18:14:25 +00002213/// getVariableArrayType - Returns a non-unique reference to the type for a
2214/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002215QualType ASTContext::getVariableArrayType(QualType EltTy,
2216 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002217 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002218 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002219 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002220 // Since we don't unique expressions, it isn't possible to unique VLA's
2221 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002222 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002223
John McCall33ddac02011-01-19 10:06:00 +00002224 // Be sure to pull qualifiers off the element type.
2225 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2226 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002227 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002228 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002229 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002230 }
2231
John McCall90d1c2d2009-09-24 23:30:46 +00002232 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002233 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002234
2235 VariableArrayTypes.push_back(New);
2236 Types.push_back(New);
2237 return QualType(New, 0);
2238}
2239
Douglas Gregor4619e432008-12-05 23:32:09 +00002240/// getDependentSizedArrayType - Returns a non-unique reference to
2241/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002242/// type.
John McCall33ddac02011-01-19 10:06:00 +00002243QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2244 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002245 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002246 unsigned elementTypeQuals,
2247 SourceRange brackets) const {
2248 assert((!numElements || numElements->isTypeDependent() ||
2249 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002250 "Size must be type- or value-dependent!");
2251
John McCall33ddac02011-01-19 10:06:00 +00002252 // Dependently-sized array types that do not have a specified number
2253 // of elements will have their sizes deduced from a dependent
2254 // initializer. We do no canonicalization here at all, which is okay
2255 // because they can't be used in most locations.
2256 if (!numElements) {
2257 DependentSizedArrayType *newType
2258 = new (*this, TypeAlignment)
2259 DependentSizedArrayType(*this, elementType, QualType(),
2260 numElements, ASM, elementTypeQuals,
2261 brackets);
2262 Types.push_back(newType);
2263 return QualType(newType, 0);
2264 }
2265
2266 // Otherwise, we actually build a new type every time, but we
2267 // also build a canonical type.
2268
2269 SplitQualType canonElementType = getCanonicalType(elementType).split();
2270
2271 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002272 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002273 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002274 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002275 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002276
John McCall33ddac02011-01-19 10:06:00 +00002277 // Look for an existing type with these properties.
2278 DependentSizedArrayType *canonTy =
2279 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002280
John McCall33ddac02011-01-19 10:06:00 +00002281 // If we don't have one, build one.
2282 if (!canonTy) {
2283 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002284 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002285 QualType(), numElements, ASM, elementTypeQuals,
2286 brackets);
2287 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2288 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002289 }
2290
John McCall33ddac02011-01-19 10:06:00 +00002291 // Apply qualifiers from the element type to the array.
2292 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002293 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002294
John McCall33ddac02011-01-19 10:06:00 +00002295 // If we didn't need extra canonicalization for the element type,
2296 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002297 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002298 return canon;
2299
2300 // Otherwise, we need to build a type which follows the spelling
2301 // of the element type.
2302 DependentSizedArrayType *sugaredType
2303 = new (*this, TypeAlignment)
2304 DependentSizedArrayType(*this, elementType, canon, numElements,
2305 ASM, elementTypeQuals, brackets);
2306 Types.push_back(sugaredType);
2307 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002308}
2309
John McCall33ddac02011-01-19 10:06:00 +00002310QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002311 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002312 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002313 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002314 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002315
John McCall33ddac02011-01-19 10:06:00 +00002316 void *insertPos = 0;
2317 if (IncompleteArrayType *iat =
2318 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2319 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002320
2321 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002322 // either, so fill in the canonical type field. We also have to pull
2323 // qualifiers off the element type.
2324 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002325
John McCall33ddac02011-01-19 10:06:00 +00002326 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2327 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002328 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002329 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002330 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002331
2332 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002333 IncompleteArrayType *existing =
2334 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2335 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002336 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002337
John McCall33ddac02011-01-19 10:06:00 +00002338 IncompleteArrayType *newType = new (*this, TypeAlignment)
2339 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002340
John McCall33ddac02011-01-19 10:06:00 +00002341 IncompleteArrayTypes.InsertNode(newType, insertPos);
2342 Types.push_back(newType);
2343 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002344}
2345
Steve Naroff91fcddb2007-07-18 18:00:27 +00002346/// getVectorType - Return the unique reference to a vector type of
2347/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002348QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002349 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002350 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002351
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002352 // Check if we've already instantiated a vector of this type.
2353 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002354 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002355
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002356 void *InsertPos = 0;
2357 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2358 return QualType(VTP, 0);
2359
2360 // If the element type isn't canonical, this won't be a canonical type either,
2361 // so fill in the canonical type field.
2362 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002363 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002364 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002365
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002366 // Get the new insert position for the node we care about.
2367 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002368 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002369 }
John McCall90d1c2d2009-09-24 23:30:46 +00002370 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002371 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002372 VectorTypes.InsertNode(New, InsertPos);
2373 Types.push_back(New);
2374 return QualType(New, 0);
2375}
2376
Nate Begemance4d7fc2008-04-18 23:10:10 +00002377/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002378/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002379QualType
2380ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002381 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002382
Steve Naroff91fcddb2007-07-18 18:00:27 +00002383 // Check if we've already instantiated a vector of this type.
2384 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002385 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002386 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002387 void *InsertPos = 0;
2388 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2389 return QualType(VTP, 0);
2390
2391 // If the element type isn't canonical, this won't be a canonical type either,
2392 // so fill in the canonical type field.
2393 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002394 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002395 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002396
Steve Naroff91fcddb2007-07-18 18:00:27 +00002397 // Get the new insert position for the node we care about.
2398 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002399 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002400 }
John McCall90d1c2d2009-09-24 23:30:46 +00002401 ExtVectorType *New = new (*this, TypeAlignment)
2402 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002403 VectorTypes.InsertNode(New, InsertPos);
2404 Types.push_back(New);
2405 return QualType(New, 0);
2406}
2407
Jay Foad39c79802011-01-12 09:06:06 +00002408QualType
2409ASTContext::getDependentSizedExtVectorType(QualType vecType,
2410 Expr *SizeExpr,
2411 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002412 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002413 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002414 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002415
Douglas Gregor352169a2009-07-31 03:54:25 +00002416 void *InsertPos = 0;
2417 DependentSizedExtVectorType *Canon
2418 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2419 DependentSizedExtVectorType *New;
2420 if (Canon) {
2421 // We already have a canonical version of this array type; use it as
2422 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002423 New = new (*this, TypeAlignment)
2424 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2425 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002426 } else {
2427 QualType CanonVecTy = getCanonicalType(vecType);
2428 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002429 New = new (*this, TypeAlignment)
2430 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2431 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002432
2433 DependentSizedExtVectorType *CanonCheck
2434 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2435 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2436 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002437 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2438 } else {
2439 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2440 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002441 New = new (*this, TypeAlignment)
2442 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002443 }
2444 }
Mike Stump11289f42009-09-09 15:08:12 +00002445
Douglas Gregor758a8692009-06-17 21:51:59 +00002446 Types.push_back(New);
2447 return QualType(New, 0);
2448}
2449
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002450/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002451///
Jay Foad39c79802011-01-12 09:06:06 +00002452QualType
2453ASTContext::getFunctionNoProtoType(QualType ResultTy,
2454 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002455 const CallingConv DefaultCC = Info.getCC();
2456 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2457 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002458 // Unique functions, to guarantee there is only one function of a particular
2459 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002460 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002461 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002462
Chris Lattner47955de2007-01-27 08:37:20 +00002463 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002464 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002465 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002466 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002467
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002468 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002469 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002470 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002471 Canonical =
2472 getFunctionNoProtoType(getCanonicalType(ResultTy),
2473 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002474
Chris Lattner47955de2007-01-27 08:37:20 +00002475 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002476 FunctionNoProtoType *NewIP =
2477 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002478 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002479 }
Mike Stump11289f42009-09-09 15:08:12 +00002480
Roman Divacky65b88cd2011-03-01 17:40:53 +00002481 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002482 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002483 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002484 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002485 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002486 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002487}
2488
2489/// getFunctionType - Return a normal function type with a typed argument
2490/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002491QualType
2492ASTContext::getFunctionType(QualType ResultTy,
2493 const QualType *ArgArray, unsigned NumArgs,
2494 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002495 // Unique functions, to guarantee there is only one function of a particular
2496 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002497 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002498 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002499
2500 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002501 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002502 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002503 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002504
2505 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002506 bool isCanonical =
2507 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2508 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002509 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002510 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002511 isCanonical = false;
2512
Roman Divacky65b88cd2011-03-01 17:40:53 +00002513 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2514 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2515 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002516
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002517 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002518 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002519 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002520 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002521 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002522 CanonicalArgs.reserve(NumArgs);
2523 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002524 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002525
John McCalldb40c7f2010-12-14 08:05:40 +00002526 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002527 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002528 CanonicalEPI.ExceptionSpecType = EST_None;
2529 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002530 CanonicalEPI.ExtInfo
2531 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2532
Chris Lattner76a00cf2008-04-06 22:59:24 +00002533 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002534 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002535 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002536
Chris Lattnerfd4de792007-01-27 01:15:32 +00002537 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002538 FunctionProtoType *NewIP =
2539 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002540 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002541 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002542
John McCall31168b02011-06-15 23:02:42 +00002543 // FunctionProtoType objects are allocated with extra bytes after
2544 // them for three variable size arrays at the end:
2545 // - parameter types
2546 // - exception types
2547 // - consumed-arguments flags
2548 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002549 // expression, or information used to resolve the exception
2550 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002551 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002552 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002553 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002554 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002555 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002556 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002557 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002558 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002559 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2560 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002561 }
John McCall31168b02011-06-15 23:02:42 +00002562 if (EPI.ConsumedArguments)
2563 Size += NumArgs * sizeof(bool);
2564
John McCalldb40c7f2010-12-14 08:05:40 +00002565 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002566 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2567 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002568 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002569 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002570 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002571 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002572}
Chris Lattneref51c202006-11-10 07:17:23 +00002573
John McCalle78aac42010-03-10 03:28:59 +00002574#ifndef NDEBUG
2575static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2576 if (!isa<CXXRecordDecl>(D)) return false;
2577 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2578 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2579 return true;
2580 if (RD->getDescribedClassTemplate() &&
2581 !isa<ClassTemplateSpecializationDecl>(RD))
2582 return true;
2583 return false;
2584}
2585#endif
2586
2587/// getInjectedClassNameType - Return the unique reference to the
2588/// injected class name type for the specified templated declaration.
2589QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002590 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002591 assert(NeedsInjectedClassNameType(Decl));
2592 if (Decl->TypeForDecl) {
2593 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002594 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002595 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2596 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2597 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2598 } else {
John McCall424cec92011-01-19 06:33:43 +00002599 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002600 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002601 Decl->TypeForDecl = newType;
2602 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002603 }
2604 return QualType(Decl->TypeForDecl, 0);
2605}
2606
Douglas Gregor83a586e2008-04-13 21:07:44 +00002607/// getTypeDeclType - Return the unique reference to the type for the
2608/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002609QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002610 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002611 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002612
Richard Smithdda56e42011-04-15 14:24:37 +00002613 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002614 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002615
John McCall96f0b5f2010-03-10 06:48:02 +00002616 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2617 "Template type parameter types are always available.");
2618
John McCall81e38502010-02-16 03:57:14 +00002619 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002620 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002621 "struct/union has previous declaration");
2622 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002623 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002624 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002625 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002626 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002627 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002628 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002629 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002630 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2631 Decl->TypeForDecl = newType;
2632 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002633 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002634 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002635
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002636 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002637}
2638
Chris Lattner32d920b2007-01-26 02:01:53 +00002639/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002640/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002641QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002642ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2643 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002644 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002645
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002646 if (Canonical.isNull())
2647 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002648 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002649 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002650 Decl->TypeForDecl = newType;
2651 Types.push_back(newType);
2652 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002653}
2654
Jay Foad39c79802011-01-12 09:06:06 +00002655QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002656 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2657
Douglas Gregorec9fd132012-01-14 16:38:05 +00002658 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002659 if (PrevDecl->TypeForDecl)
2660 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2661
John McCall424cec92011-01-19 06:33:43 +00002662 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2663 Decl->TypeForDecl = newType;
2664 Types.push_back(newType);
2665 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002666}
2667
Jay Foad39c79802011-01-12 09:06:06 +00002668QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002669 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2670
Douglas Gregorec9fd132012-01-14 16:38:05 +00002671 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002672 if (PrevDecl->TypeForDecl)
2673 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2674
John McCall424cec92011-01-19 06:33:43 +00002675 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2676 Decl->TypeForDecl = newType;
2677 Types.push_back(newType);
2678 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002679}
2680
John McCall81904512011-01-06 01:58:22 +00002681QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2682 QualType modifiedType,
2683 QualType equivalentType) {
2684 llvm::FoldingSetNodeID id;
2685 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2686
2687 void *insertPos = 0;
2688 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2689 if (type) return QualType(type, 0);
2690
2691 QualType canon = getCanonicalType(equivalentType);
2692 type = new (*this, TypeAlignment)
2693 AttributedType(canon, attrKind, modifiedType, equivalentType);
2694
2695 Types.push_back(type);
2696 AttributedTypes.InsertNode(type, insertPos);
2697
2698 return QualType(type, 0);
2699}
2700
2701
John McCallcebee162009-10-18 09:09:24 +00002702/// \brief Retrieve a substitution-result type.
2703QualType
2704ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002705 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002706 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002707 && "replacement types must always be canonical");
2708
2709 llvm::FoldingSetNodeID ID;
2710 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2711 void *InsertPos = 0;
2712 SubstTemplateTypeParmType *SubstParm
2713 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2714
2715 if (!SubstParm) {
2716 SubstParm = new (*this, TypeAlignment)
2717 SubstTemplateTypeParmType(Parm, Replacement);
2718 Types.push_back(SubstParm);
2719 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2720 }
2721
2722 return QualType(SubstParm, 0);
2723}
2724
Douglas Gregorada4b792011-01-14 02:55:32 +00002725/// \brief Retrieve a
2726QualType ASTContext::getSubstTemplateTypeParmPackType(
2727 const TemplateTypeParmType *Parm,
2728 const TemplateArgument &ArgPack) {
2729#ifndef NDEBUG
2730 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2731 PEnd = ArgPack.pack_end();
2732 P != PEnd; ++P) {
2733 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2734 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2735 }
2736#endif
2737
2738 llvm::FoldingSetNodeID ID;
2739 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2740 void *InsertPos = 0;
2741 if (SubstTemplateTypeParmPackType *SubstParm
2742 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2743 return QualType(SubstParm, 0);
2744
2745 QualType Canon;
2746 if (!Parm->isCanonicalUnqualified()) {
2747 Canon = getCanonicalType(QualType(Parm, 0));
2748 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2749 ArgPack);
2750 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2751 }
2752
2753 SubstTemplateTypeParmPackType *SubstParm
2754 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2755 ArgPack);
2756 Types.push_back(SubstParm);
2757 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2758 return QualType(SubstParm, 0);
2759}
2760
Douglas Gregoreff93e02009-02-05 23:33:38 +00002761/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002762/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002763/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002764QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002765 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002766 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002767 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002768 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002769 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002770 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002771 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2772
2773 if (TypeParm)
2774 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002775
Chandler Carruth08836322011-05-01 00:51:33 +00002776 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002777 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002778 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002779
2780 TemplateTypeParmType *TypeCheck
2781 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2782 assert(!TypeCheck && "Template type parameter canonical type broken");
2783 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002784 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002785 TypeParm = new (*this, TypeAlignment)
2786 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002787
2788 Types.push_back(TypeParm);
2789 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2790
2791 return QualType(TypeParm, 0);
2792}
2793
John McCalle78aac42010-03-10 03:28:59 +00002794TypeSourceInfo *
2795ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2796 SourceLocation NameLoc,
2797 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002798 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002799 assert(!Name.getAsDependentTemplateName() &&
2800 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002801 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002802
2803 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2804 TemplateSpecializationTypeLoc TL
2805 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002806 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002807 TL.setTemplateNameLoc(NameLoc);
2808 TL.setLAngleLoc(Args.getLAngleLoc());
2809 TL.setRAngleLoc(Args.getRAngleLoc());
2810 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2811 TL.setArgLocInfo(i, Args[i].getLocInfo());
2812 return DI;
2813}
2814
Mike Stump11289f42009-09-09 15:08:12 +00002815QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002816ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002817 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002818 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002819 assert(!Template.getAsDependentTemplateName() &&
2820 "No dependent template names here!");
2821
John McCall6b51f282009-11-23 01:53:49 +00002822 unsigned NumArgs = Args.size();
2823
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002824 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002825 ArgVec.reserve(NumArgs);
2826 for (unsigned i = 0; i != NumArgs; ++i)
2827 ArgVec.push_back(Args[i].getArgument());
2828
John McCall2408e322010-04-27 00:57:59 +00002829 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002830 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002831}
2832
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002833#ifndef NDEBUG
2834static bool hasAnyPackExpansions(const TemplateArgument *Args,
2835 unsigned NumArgs) {
2836 for (unsigned I = 0; I != NumArgs; ++I)
2837 if (Args[I].isPackExpansion())
2838 return true;
2839
2840 return true;
2841}
2842#endif
2843
John McCall0ad16662009-10-29 08:12:44 +00002844QualType
2845ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002846 const TemplateArgument *Args,
2847 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002848 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002849 assert(!Template.getAsDependentTemplateName() &&
2850 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002851 // Look through qualified template names.
2852 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2853 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002854
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002855 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002856 Template.getAsTemplateDecl() &&
2857 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002858 QualType CanonType;
2859 if (!Underlying.isNull())
2860 CanonType = getCanonicalType(Underlying);
2861 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002862 // We can get here with an alias template when the specialization contains
2863 // a pack expansion that does not match up with a parameter pack.
2864 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2865 "Caller must compute aliased type");
2866 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002867 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2868 NumArgs);
2869 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002870
Douglas Gregora8e02e72009-07-28 23:00:59 +00002871 // Allocate the (non-canonical) template specialization type, but don't
2872 // try to unique it: these types typically have location information that
2873 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002874 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2875 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002876 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002877 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002878 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002879 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2880 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002881
Douglas Gregor8bf42052009-02-09 18:46:07 +00002882 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002883 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002884}
2885
Mike Stump11289f42009-09-09 15:08:12 +00002886QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002887ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2888 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002889 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002890 assert(!Template.getAsDependentTemplateName() &&
2891 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002892
Douglas Gregore29139c2011-03-03 17:04:51 +00002893 // Look through qualified template names.
2894 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2895 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002896
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002897 // Build the canonical template specialization type.
2898 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002899 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002900 CanonArgs.reserve(NumArgs);
2901 for (unsigned I = 0; I != NumArgs; ++I)
2902 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2903
2904 // Determine whether this canonical template specialization type already
2905 // exists.
2906 llvm::FoldingSetNodeID ID;
2907 TemplateSpecializationType::Profile(ID, CanonTemplate,
2908 CanonArgs.data(), NumArgs, *this);
2909
2910 void *InsertPos = 0;
2911 TemplateSpecializationType *Spec
2912 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2913
2914 if (!Spec) {
2915 // Allocate a new canonical template specialization type.
2916 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2917 sizeof(TemplateArgument) * NumArgs),
2918 TypeAlignment);
2919 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2920 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002921 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002922 Types.push_back(Spec);
2923 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2924 }
2925
2926 assert(Spec->isDependentType() &&
2927 "Non-dependent template-id type must have a canonical type");
2928 return QualType(Spec, 0);
2929}
2930
2931QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002932ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2933 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002934 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002935 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002936 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002937
2938 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002939 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002940 if (T)
2941 return QualType(T, 0);
2942
Douglas Gregorc42075a2010-02-04 18:10:26 +00002943 QualType Canon = NamedType;
2944 if (!Canon.isCanonical()) {
2945 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002946 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2947 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002948 (void)CheckT;
2949 }
2950
Abramo Bagnara6150c882010-05-11 21:36:43 +00002951 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002952 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002953 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002954 return QualType(T, 0);
2955}
2956
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002957QualType
Jay Foad39c79802011-01-12 09:06:06 +00002958ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002959 llvm::FoldingSetNodeID ID;
2960 ParenType::Profile(ID, InnerType);
2961
2962 void *InsertPos = 0;
2963 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2964 if (T)
2965 return QualType(T, 0);
2966
2967 QualType Canon = InnerType;
2968 if (!Canon.isCanonical()) {
2969 Canon = getCanonicalType(InnerType);
2970 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2971 assert(!CheckT && "Paren canonical type broken");
2972 (void)CheckT;
2973 }
2974
2975 T = new (*this) ParenType(InnerType, Canon);
2976 Types.push_back(T);
2977 ParenTypes.InsertNode(T, InsertPos);
2978 return QualType(T, 0);
2979}
2980
Douglas Gregor02085352010-03-31 20:19:30 +00002981QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2982 NestedNameSpecifier *NNS,
2983 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002984 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002985 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2986
2987 if (Canon.isNull()) {
2988 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002989 ElaboratedTypeKeyword CanonKeyword = Keyword;
2990 if (Keyword == ETK_None)
2991 CanonKeyword = ETK_Typename;
2992
2993 if (CanonNNS != NNS || CanonKeyword != Keyword)
2994 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002995 }
2996
2997 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002998 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002999
3000 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003001 DependentNameType *T
3002 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003003 if (T)
3004 return QualType(T, 0);
3005
Douglas Gregor02085352010-03-31 20:19:30 +00003006 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003007 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003008 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003009 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003010}
3011
Mike Stump11289f42009-09-09 15:08:12 +00003012QualType
John McCallc392f372010-06-11 00:33:02 +00003013ASTContext::getDependentTemplateSpecializationType(
3014 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003015 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003016 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003017 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003018 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003019 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003020 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3021 ArgCopy.push_back(Args[I].getArgument());
3022 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3023 ArgCopy.size(),
3024 ArgCopy.data());
3025}
3026
3027QualType
3028ASTContext::getDependentTemplateSpecializationType(
3029 ElaboratedTypeKeyword Keyword,
3030 NestedNameSpecifier *NNS,
3031 const IdentifierInfo *Name,
3032 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003033 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003034 assert((!NNS || NNS->isDependent()) &&
3035 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003036
Douglas Gregorc42075a2010-02-04 18:10:26 +00003037 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003038 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3039 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003040
3041 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003042 DependentTemplateSpecializationType *T
3043 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003044 if (T)
3045 return QualType(T, 0);
3046
John McCallc392f372010-06-11 00:33:02 +00003047 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003048
John McCallc392f372010-06-11 00:33:02 +00003049 ElaboratedTypeKeyword CanonKeyword = Keyword;
3050 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3051
3052 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003053 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003054 for (unsigned I = 0; I != NumArgs; ++I) {
3055 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3056 if (!CanonArgs[I].structurallyEquals(Args[I]))
3057 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003058 }
3059
John McCallc392f372010-06-11 00:33:02 +00003060 QualType Canon;
3061 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3062 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3063 Name, NumArgs,
3064 CanonArgs.data());
3065
3066 // Find the insert position again.
3067 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3068 }
3069
3070 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3071 sizeof(TemplateArgument) * NumArgs),
3072 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003073 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003074 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003075 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003076 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003077 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003078}
3079
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003080QualType ASTContext::getPackExpansionType(QualType Pattern,
3081 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003082 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003083 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003084
3085 assert(Pattern->containsUnexpandedParameterPack() &&
3086 "Pack expansions must expand one or more parameter packs");
3087 void *InsertPos = 0;
3088 PackExpansionType *T
3089 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3090 if (T)
3091 return QualType(T, 0);
3092
3093 QualType Canon;
3094 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003095 Canon = getCanonicalType(Pattern);
3096 // The canonical type might not contain an unexpanded parameter pack, if it
3097 // contains an alias template specialization which ignores one of its
3098 // parameters.
3099 if (Canon->containsUnexpandedParameterPack()) {
3100 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003101
Richard Smith68eea502012-07-16 00:20:35 +00003102 // Find the insert position again, in case we inserted an element into
3103 // PackExpansionTypes and invalidated our insert position.
3104 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3105 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003106 }
3107
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003108 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003109 Types.push_back(T);
3110 PackExpansionTypes.InsertNode(T, InsertPos);
3111 return QualType(T, 0);
3112}
3113
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003114/// CmpProtocolNames - Comparison predicate for sorting protocols
3115/// alphabetically.
3116static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3117 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003118 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003119}
3120
John McCall8b07ec22010-05-15 11:32:37 +00003121static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003122 unsigned NumProtocols) {
3123 if (NumProtocols == 0) return true;
3124
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003125 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3126 return false;
3127
John McCallfc93cf92009-10-22 22:37:11 +00003128 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003129 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3130 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003131 return false;
3132 return true;
3133}
3134
3135static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003136 unsigned &NumProtocols) {
3137 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003138
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003139 // Sort protocols, keyed by name.
3140 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3141
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003142 // Canonicalize.
3143 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3144 Protocols[I] = Protocols[I]->getCanonicalDecl();
3145
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003146 // Remove duplicates.
3147 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3148 NumProtocols = ProtocolsEnd-Protocols;
3149}
3150
John McCall8b07ec22010-05-15 11:32:37 +00003151QualType ASTContext::getObjCObjectType(QualType BaseType,
3152 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003153 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003154 // If the base type is an interface and there aren't any protocols
3155 // to add, then the interface type will do just fine.
3156 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3157 return BaseType;
3158
3159 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003160 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003161 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003162 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003163 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3164 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003165
John McCall8b07ec22010-05-15 11:32:37 +00003166 // Build the canonical type, which has the canonical base type and
3167 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003168 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003169 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3170 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3171 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003172 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003173 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003174 unsigned UniqueCount = NumProtocols;
3175
John McCallfc93cf92009-10-22 22:37:11 +00003176 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003177 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3178 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003179 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003180 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3181 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003182 }
3183
3184 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003185 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3186 }
3187
3188 unsigned Size = sizeof(ObjCObjectTypeImpl);
3189 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3190 void *Mem = Allocate(Size, TypeAlignment);
3191 ObjCObjectTypeImpl *T =
3192 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3193
3194 Types.push_back(T);
3195 ObjCObjectTypes.InsertNode(T, InsertPos);
3196 return QualType(T, 0);
3197}
3198
3199/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3200/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003201QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003202 llvm::FoldingSetNodeID ID;
3203 ObjCObjectPointerType::Profile(ID, ObjectT);
3204
3205 void *InsertPos = 0;
3206 if (ObjCObjectPointerType *QT =
3207 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3208 return QualType(QT, 0);
3209
3210 // Find the canonical object type.
3211 QualType Canonical;
3212 if (!ObjectT.isCanonical()) {
3213 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3214
3215 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003216 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3217 }
3218
Douglas Gregorf85bee62010-02-08 22:59:26 +00003219 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003220 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3221 ObjCObjectPointerType *QType =
3222 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003223
Steve Narofffb4330f2009-06-17 22:40:22 +00003224 Types.push_back(QType);
3225 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003226 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003227}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003228
Douglas Gregor1c283312010-08-11 12:19:30 +00003229/// getObjCInterfaceType - Return the unique reference to the type for the
3230/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003231QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3232 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003233 if (Decl->TypeForDecl)
3234 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003235
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003236 if (PrevDecl) {
3237 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3238 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3239 return QualType(PrevDecl->TypeForDecl, 0);
3240 }
3241
Douglas Gregor7671e532011-12-16 16:34:57 +00003242 // Prefer the definition, if there is one.
3243 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3244 Decl = Def;
3245
Douglas Gregor1c283312010-08-11 12:19:30 +00003246 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3247 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3248 Decl->TypeForDecl = T;
3249 Types.push_back(T);
3250 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003251}
3252
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003253/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3254/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003255/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003256/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003257/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003258QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003259 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003260 if (tofExpr->isTypeDependent()) {
3261 llvm::FoldingSetNodeID ID;
3262 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003263
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003264 void *InsertPos = 0;
3265 DependentTypeOfExprType *Canon
3266 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3267 if (Canon) {
3268 // We already have a "canonical" version of an identical, dependent
3269 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003270 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003271 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003272 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003273 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003274 Canon
3275 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003276 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3277 toe = Canon;
3278 }
3279 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003280 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003281 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003282 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003283 Types.push_back(toe);
3284 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003285}
3286
Steve Naroffa773cd52007-08-01 18:02:17 +00003287/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3288/// TypeOfType AST's. The only motivation to unique these nodes would be
3289/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003290/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003291/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003292QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003293 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003294 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003295 Types.push_back(tot);
3296 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003297}
3298
Anders Carlssonad6bd352009-06-24 21:24:56 +00003299
Anders Carlsson81df7b82009-06-24 19:06:50 +00003300/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3301/// DecltypeType AST's. The only motivation to unique these nodes would be
3302/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003303/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003304/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003305QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003306 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003307
3308 // C++0x [temp.type]p2:
3309 // If an expression e involves a template parameter, decltype(e) denotes a
3310 // unique dependent type. Two such decltype-specifiers refer to the same
3311 // type only if their expressions are equivalent (14.5.6.1).
3312 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003313 llvm::FoldingSetNodeID ID;
3314 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003315
Douglas Gregora21f6c32009-07-30 23:36:40 +00003316 void *InsertPos = 0;
3317 DependentDecltypeType *Canon
3318 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3319 if (Canon) {
3320 // We already have a "canonical" version of an equivalent, dependent
3321 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003322 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003323 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003324 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003325 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003326 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003327 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3328 dt = Canon;
3329 }
3330 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003331 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3332 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003333 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003334 Types.push_back(dt);
3335 return QualType(dt, 0);
3336}
3337
Alexis Hunte852b102011-05-24 22:41:36 +00003338/// getUnaryTransformationType - We don't unique these, since the memory
3339/// savings are minimal and these are rare.
3340QualType ASTContext::getUnaryTransformType(QualType BaseType,
3341 QualType UnderlyingType,
3342 UnaryTransformType::UTTKind Kind)
3343 const {
3344 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003345 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3346 Kind,
3347 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003348 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003349 Types.push_back(Ty);
3350 return QualType(Ty, 0);
3351}
3352
Richard Smithb2bc2e62011-02-21 20:05:19 +00003353/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003354QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003355 void *InsertPos = 0;
3356 if (!DeducedType.isNull()) {
3357 // Look in the folding set for an existing type.
3358 llvm::FoldingSetNodeID ID;
3359 AutoType::Profile(ID, DeducedType);
3360 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3361 return QualType(AT, 0);
3362 }
3363
3364 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3365 Types.push_back(AT);
3366 if (InsertPos)
3367 AutoTypes.InsertNode(AT, InsertPos);
3368 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003369}
3370
Eli Friedman0dfb8892011-10-06 23:00:33 +00003371/// getAtomicType - Return the uniqued reference to the atomic type for
3372/// the given value type.
3373QualType ASTContext::getAtomicType(QualType T) const {
3374 // Unique pointers, to guarantee there is only one pointer of a particular
3375 // structure.
3376 llvm::FoldingSetNodeID ID;
3377 AtomicType::Profile(ID, T);
3378
3379 void *InsertPos = 0;
3380 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3381 return QualType(AT, 0);
3382
3383 // If the atomic value type isn't canonical, this won't be a canonical type
3384 // either, so fill in the canonical type field.
3385 QualType Canonical;
3386 if (!T.isCanonical()) {
3387 Canonical = getAtomicType(getCanonicalType(T));
3388
3389 // Get the new insert position for the node we care about.
3390 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3391 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3392 }
3393 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3394 Types.push_back(New);
3395 AtomicTypes.InsertNode(New, InsertPos);
3396 return QualType(New, 0);
3397}
3398
Richard Smith02e85f32011-04-14 22:09:26 +00003399/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3400QualType ASTContext::getAutoDeductType() const {
3401 if (AutoDeductTy.isNull())
3402 AutoDeductTy = getAutoType(QualType());
3403 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3404 return AutoDeductTy;
3405}
3406
3407/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3408QualType ASTContext::getAutoRRefDeductType() const {
3409 if (AutoRRefDeductTy.isNull())
3410 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3411 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3412 return AutoRRefDeductTy;
3413}
3414
Chris Lattnerfb072462007-01-23 05:45:31 +00003415/// getTagDeclType - Return the unique reference to the type for the
3416/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003417QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003418 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003419 // FIXME: What is the design on getTagDeclType when it requires casting
3420 // away const? mutable?
3421 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003422}
3423
Mike Stump11289f42009-09-09 15:08:12 +00003424/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3425/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3426/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003427CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003428 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003429}
Chris Lattnerfb072462007-01-23 05:45:31 +00003430
Hans Wennborg27541db2011-10-27 08:29:09 +00003431/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3432CanQualType ASTContext::getIntMaxType() const {
3433 return getFromTargetType(Target->getIntMaxType());
3434}
3435
3436/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3437CanQualType ASTContext::getUIntMaxType() const {
3438 return getFromTargetType(Target->getUIntMaxType());
3439}
3440
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003441/// getSignedWCharType - Return the type of "signed wchar_t".
3442/// Used when in C++, as a GCC extension.
3443QualType ASTContext::getSignedWCharType() const {
3444 // FIXME: derive from "Target" ?
3445 return WCharTy;
3446}
3447
3448/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3449/// Used when in C++, as a GCC extension.
3450QualType ASTContext::getUnsignedWCharType() const {
3451 // FIXME: derive from "Target" ?
3452 return UnsignedIntTy;
3453}
3454
Hans Wennborg27541db2011-10-27 08:29:09 +00003455/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003456/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3457QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003458 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003459}
3460
Chris Lattnera21ad802008-04-02 05:18:44 +00003461//===----------------------------------------------------------------------===//
3462// Type Operators
3463//===----------------------------------------------------------------------===//
3464
Jay Foad39c79802011-01-12 09:06:06 +00003465CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003466 // Push qualifiers into arrays, and then discard any remaining
3467 // qualifiers.
3468 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003469 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003470 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003471 QualType Result;
3472 if (isa<ArrayType>(Ty)) {
3473 Result = getArrayDecayedType(QualType(Ty,0));
3474 } else if (isa<FunctionType>(Ty)) {
3475 Result = getPointerType(QualType(Ty, 0));
3476 } else {
3477 Result = QualType(Ty, 0);
3478 }
3479
3480 return CanQualType::CreateUnsafe(Result);
3481}
3482
John McCall6c9dd522011-01-18 07:41:22 +00003483QualType ASTContext::getUnqualifiedArrayType(QualType type,
3484 Qualifiers &quals) {
3485 SplitQualType splitType = type.getSplitUnqualifiedType();
3486
3487 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3488 // the unqualified desugared type and then drops it on the floor.
3489 // We then have to strip that sugar back off with
3490 // getUnqualifiedDesugaredType(), which is silly.
3491 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003492 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003493
3494 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003495 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003496 quals = splitType.Quals;
3497 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003498 }
3499
John McCall6c9dd522011-01-18 07:41:22 +00003500 // Otherwise, recurse on the array's element type.
3501 QualType elementType = AT->getElementType();
3502 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3503
3504 // If that didn't change the element type, AT has no qualifiers, so we
3505 // can just use the results in splitType.
3506 if (elementType == unqualElementType) {
3507 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003508 quals = splitType.Quals;
3509 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003510 }
3511
3512 // Otherwise, add in the qualifiers from the outermost type, then
3513 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003514 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003515
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003516 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003517 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003518 CAT->getSizeModifier(), 0);
3519 }
3520
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003521 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003522 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003523 }
3524
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003525 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003526 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003527 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003528 VAT->getSizeModifier(),
3529 VAT->getIndexTypeCVRQualifiers(),
3530 VAT->getBracketsRange());
3531 }
3532
3533 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003534 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003535 DSAT->getSizeModifier(), 0,
3536 SourceRange());
3537}
3538
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003539/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3540/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3541/// they point to and return true. If T1 and T2 aren't pointer types
3542/// or pointer-to-member types, or if they are not similar at this
3543/// level, returns false and leaves T1 and T2 unchanged. Top-level
3544/// qualifiers on T1 and T2 are ignored. This function will typically
3545/// be called in a loop that successively "unwraps" pointer and
3546/// pointer-to-member types to compare them at each level.
3547bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3548 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3549 *T2PtrType = T2->getAs<PointerType>();
3550 if (T1PtrType && T2PtrType) {
3551 T1 = T1PtrType->getPointeeType();
3552 T2 = T2PtrType->getPointeeType();
3553 return true;
3554 }
3555
3556 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3557 *T2MPType = T2->getAs<MemberPointerType>();
3558 if (T1MPType && T2MPType &&
3559 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3560 QualType(T2MPType->getClass(), 0))) {
3561 T1 = T1MPType->getPointeeType();
3562 T2 = T2MPType->getPointeeType();
3563 return true;
3564 }
3565
David Blaikiebbafb8a2012-03-11 07:00:24 +00003566 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003567 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3568 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3569 if (T1OPType && T2OPType) {
3570 T1 = T1OPType->getPointeeType();
3571 T2 = T2OPType->getPointeeType();
3572 return true;
3573 }
3574 }
3575
3576 // FIXME: Block pointers, too?
3577
3578 return false;
3579}
3580
Jay Foad39c79802011-01-12 09:06:06 +00003581DeclarationNameInfo
3582ASTContext::getNameForTemplate(TemplateName Name,
3583 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003584 switch (Name.getKind()) {
3585 case TemplateName::QualifiedTemplate:
3586 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003587 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003588 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3589 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003590
John McCalld9dfe3a2011-06-30 08:33:18 +00003591 case TemplateName::OverloadedTemplate: {
3592 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3593 // DNInfo work in progress: CHECKME: what about DNLoc?
3594 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3595 }
3596
3597 case TemplateName::DependentTemplate: {
3598 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003599 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003600 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003601 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3602 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003603 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003604 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3605 // DNInfo work in progress: FIXME: source locations?
3606 DeclarationNameLoc DNLoc;
3607 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3608 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3609 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003610 }
3611 }
3612
John McCalld9dfe3a2011-06-30 08:33:18 +00003613 case TemplateName::SubstTemplateTemplateParm: {
3614 SubstTemplateTemplateParmStorage *subst
3615 = Name.getAsSubstTemplateTemplateParm();
3616 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3617 NameLoc);
3618 }
3619
3620 case TemplateName::SubstTemplateTemplateParmPack: {
3621 SubstTemplateTemplateParmPackStorage *subst
3622 = Name.getAsSubstTemplateTemplateParmPack();
3623 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3624 NameLoc);
3625 }
3626 }
3627
3628 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003629}
3630
Jay Foad39c79802011-01-12 09:06:06 +00003631TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003632 switch (Name.getKind()) {
3633 case TemplateName::QualifiedTemplate:
3634 case TemplateName::Template: {
3635 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003636 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003637 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003638 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3639
3640 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003641 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003642 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003643
John McCalld9dfe3a2011-06-30 08:33:18 +00003644 case TemplateName::OverloadedTemplate:
3645 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003646
John McCalld9dfe3a2011-06-30 08:33:18 +00003647 case TemplateName::DependentTemplate: {
3648 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3649 assert(DTN && "Non-dependent template names must refer to template decls.");
3650 return DTN->CanonicalTemplateName;
3651 }
3652
3653 case TemplateName::SubstTemplateTemplateParm: {
3654 SubstTemplateTemplateParmStorage *subst
3655 = Name.getAsSubstTemplateTemplateParm();
3656 return getCanonicalTemplateName(subst->getReplacement());
3657 }
3658
3659 case TemplateName::SubstTemplateTemplateParmPack: {
3660 SubstTemplateTemplateParmPackStorage *subst
3661 = Name.getAsSubstTemplateTemplateParmPack();
3662 TemplateTemplateParmDecl *canonParameter
3663 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3664 TemplateArgument canonArgPack
3665 = getCanonicalTemplateArgument(subst->getArgumentPack());
3666 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3667 }
3668 }
3669
3670 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003671}
3672
Douglas Gregoradee3e32009-11-11 23:06:43 +00003673bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3674 X = getCanonicalTemplateName(X);
3675 Y = getCanonicalTemplateName(Y);
3676 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3677}
3678
Mike Stump11289f42009-09-09 15:08:12 +00003679TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003680ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003681 switch (Arg.getKind()) {
3682 case TemplateArgument::Null:
3683 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003684
Douglas Gregora8e02e72009-07-28 23:00:59 +00003685 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003686 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003687
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003688 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003689 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3690 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003691 }
Mike Stump11289f42009-09-09 15:08:12 +00003692
Eli Friedmanb826a002012-09-26 02:36:12 +00003693 case TemplateArgument::NullPtr:
3694 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3695 /*isNullPtr*/true);
3696
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003697 case TemplateArgument::Template:
3698 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003699
3700 case TemplateArgument::TemplateExpansion:
3701 return TemplateArgument(getCanonicalTemplateName(
3702 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003703 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003704
Douglas Gregora8e02e72009-07-28 23:00:59 +00003705 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003706 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003707
Douglas Gregora8e02e72009-07-28 23:00:59 +00003708 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003709 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003710
Douglas Gregora8e02e72009-07-28 23:00:59 +00003711 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003712 if (Arg.pack_size() == 0)
3713 return Arg;
3714
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003715 TemplateArgument *CanonArgs
3716 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003717 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003718 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003719 AEnd = Arg.pack_end();
3720 A != AEnd; (void)++A, ++Idx)
3721 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003722
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003723 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003724 }
3725 }
3726
3727 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003728 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003729}
3730
Douglas Gregor333489b2009-03-27 23:10:48 +00003731NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003732ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003733 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003734 return 0;
3735
3736 switch (NNS->getKind()) {
3737 case NestedNameSpecifier::Identifier:
3738 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003739 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003740 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3741 NNS->getAsIdentifier());
3742
3743 case NestedNameSpecifier::Namespace:
3744 // A namespace is canonical; build a nested-name-specifier with
3745 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003746 return NestedNameSpecifier::Create(*this, 0,
3747 NNS->getAsNamespace()->getOriginalNamespace());
3748
3749 case NestedNameSpecifier::NamespaceAlias:
3750 // A namespace is canonical; build a nested-name-specifier with
3751 // this namespace and no prefix.
3752 return NestedNameSpecifier::Create(*this, 0,
3753 NNS->getAsNamespaceAlias()->getNamespace()
3754 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003755
3756 case NestedNameSpecifier::TypeSpec:
3757 case NestedNameSpecifier::TypeSpecWithTemplate: {
3758 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003759
3760 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3761 // break it apart into its prefix and identifier, then reconsititute those
3762 // as the canonical nested-name-specifier. This is required to canonicalize
3763 // a dependent nested-name-specifier involving typedefs of dependent-name
3764 // types, e.g.,
3765 // typedef typename T::type T1;
3766 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003767 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3768 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003769 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003770
Eli Friedman5358a0a2012-03-03 04:09:56 +00003771 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3772 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3773 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003774 return NestedNameSpecifier::Create(*this, 0, false,
3775 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003776 }
3777
3778 case NestedNameSpecifier::Global:
3779 // The global specifier is canonical and unique.
3780 return NNS;
3781 }
3782
David Blaikie8a40f702012-01-17 06:56:22 +00003783 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003784}
3785
Chris Lattner7adf0762008-08-04 07:31:14 +00003786
Jay Foad39c79802011-01-12 09:06:06 +00003787const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003788 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003789 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003790 // Handle the common positive case fast.
3791 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3792 return AT;
3793 }
Mike Stump11289f42009-09-09 15:08:12 +00003794
John McCall8ccfcb52009-09-24 19:53:00 +00003795 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003796 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003797 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003798
John McCall8ccfcb52009-09-24 19:53:00 +00003799 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003800 // implements C99 6.7.3p8: "If the specification of an array type includes
3801 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003802
Chris Lattner7adf0762008-08-04 07:31:14 +00003803 // If we get here, we either have type qualifiers on the type, or we have
3804 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003805 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003806
John McCall33ddac02011-01-19 10:06:00 +00003807 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003808 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003809
Chris Lattner7adf0762008-08-04 07:31:14 +00003810 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003811 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003812 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003813 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003814
Chris Lattner7adf0762008-08-04 07:31:14 +00003815 // Otherwise, we have an array and we have qualifiers on it. Push the
3816 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003817 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003818
Chris Lattner7adf0762008-08-04 07:31:14 +00003819 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3820 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3821 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003822 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003823 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3824 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3825 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003826 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003827
Mike Stump11289f42009-09-09 15:08:12 +00003828 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003829 = dyn_cast<DependentSizedArrayType>(ATy))
3830 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003831 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003832 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003833 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003834 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003835 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003836
Chris Lattner7adf0762008-08-04 07:31:14 +00003837 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003838 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003839 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003840 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003841 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003842 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003843}
3844
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003845QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003846 // C99 6.7.5.3p7:
3847 // A declaration of a parameter as "array of type" shall be
3848 // adjusted to "qualified pointer to type", where the type
3849 // qualifiers (if any) are those specified within the [ and ] of
3850 // the array type derivation.
3851 if (T->isArrayType())
3852 return getArrayDecayedType(T);
3853
3854 // C99 6.7.5.3p8:
3855 // A declaration of a parameter as "function returning type"
3856 // shall be adjusted to "pointer to function returning type", as
3857 // in 6.3.2.1.
3858 if (T->isFunctionType())
3859 return getPointerType(T);
3860
3861 return T;
3862}
3863
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003864QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003865 T = getVariableArrayDecayedType(T);
3866 T = getAdjustedParameterType(T);
3867 return T.getUnqualifiedType();
3868}
3869
Chris Lattnera21ad802008-04-02 05:18:44 +00003870/// getArrayDecayedType - Return the properly qualified result of decaying the
3871/// specified array type to a pointer. This operation is non-trivial when
3872/// handling typedefs etc. The canonical type of "T" must be an array type,
3873/// this returns a pointer to a properly qualified element of the array.
3874///
3875/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003876QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003877 // Get the element type with 'getAsArrayType' so that we don't lose any
3878 // typedefs in the element type of the array. This also handles propagation
3879 // of type qualifiers from the array type into the element type if present
3880 // (C99 6.7.3p8).
3881 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3882 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003883
Chris Lattner7adf0762008-08-04 07:31:14 +00003884 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003885
3886 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003887 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003888}
3889
John McCall33ddac02011-01-19 10:06:00 +00003890QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3891 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003892}
3893
John McCall33ddac02011-01-19 10:06:00 +00003894QualType ASTContext::getBaseElementType(QualType type) const {
3895 Qualifiers qs;
3896 while (true) {
3897 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003898 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003899 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003900
John McCall33ddac02011-01-19 10:06:00 +00003901 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003902 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003903 }
Mike Stump11289f42009-09-09 15:08:12 +00003904
John McCall33ddac02011-01-19 10:06:00 +00003905 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003906}
3907
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003908/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003909uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003910ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3911 uint64_t ElementCount = 1;
3912 do {
3913 ElementCount *= CA->getSize().getZExtValue();
3914 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3915 } while (CA);
3916 return ElementCount;
3917}
3918
Steve Naroff0af91202007-04-27 21:51:21 +00003919/// getFloatingRank - Return a relative rank for floating point types.
3920/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003921static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003922 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003923 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003924
John McCall9dd450b2009-09-21 23:43:11 +00003925 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3926 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003927 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003928 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003929 case BuiltinType::Float: return FloatRank;
3930 case BuiltinType::Double: return DoubleRank;
3931 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003932 }
3933}
3934
Mike Stump11289f42009-09-09 15:08:12 +00003935/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3936/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003937/// 'typeDomain' is a real floating point or complex type.
3938/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003939QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3940 QualType Domain) const {
3941 FloatingRank EltRank = getFloatingRank(Size);
3942 if (Domain->isComplexType()) {
3943 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003944 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003945 case FloatRank: return FloatComplexTy;
3946 case DoubleRank: return DoubleComplexTy;
3947 case LongDoubleRank: return LongDoubleComplexTy;
3948 }
Steve Naroff0af91202007-04-27 21:51:21 +00003949 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003950
3951 assert(Domain->isRealFloatingType() && "Unknown domain!");
3952 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003953 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003954 case FloatRank: return FloatTy;
3955 case DoubleRank: return DoubleTy;
3956 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003957 }
David Blaikief47fa302012-01-17 02:30:50 +00003958 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003959}
3960
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003961/// getFloatingTypeOrder - Compare the rank of the two specified floating
3962/// point types, ignoring the domain of the type (i.e. 'double' ==
3963/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003964/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003965int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003966 FloatingRank LHSR = getFloatingRank(LHS);
3967 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003968
Chris Lattnerb90739d2008-04-06 23:38:49 +00003969 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003970 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003971 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003972 return 1;
3973 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003974}
3975
Chris Lattner76a00cf2008-04-06 22:59:24 +00003976/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3977/// routine will assert if passed a built-in type that isn't an integer or enum,
3978/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003979unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003980 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003981
Chris Lattner76a00cf2008-04-06 22:59:24 +00003982 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003983 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003984 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003985 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003986 case BuiltinType::Char_S:
3987 case BuiltinType::Char_U:
3988 case BuiltinType::SChar:
3989 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003990 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003991 case BuiltinType::Short:
3992 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003993 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003994 case BuiltinType::Int:
3995 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003996 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003997 case BuiltinType::Long:
3998 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003999 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004000 case BuiltinType::LongLong:
4001 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004002 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004003 case BuiltinType::Int128:
4004 case BuiltinType::UInt128:
4005 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004006 }
4007}
4008
Eli Friedman629ffb92009-08-20 04:21:42 +00004009/// \brief Whether this is a promotable bitfield reference according
4010/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4011///
4012/// \returns the type this bit-field will promote to, or NULL if no
4013/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004014QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004015 if (E->isTypeDependent() || E->isValueDependent())
4016 return QualType();
4017
Eli Friedman629ffb92009-08-20 04:21:42 +00004018 FieldDecl *Field = E->getBitField();
4019 if (!Field)
4020 return QualType();
4021
4022 QualType FT = Field->getType();
4023
Richard Smithcaf33902011-10-10 18:28:20 +00004024 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004025 uint64_t IntSize = getTypeSize(IntTy);
4026 // GCC extension compatibility: if the bit-field size is less than or equal
4027 // to the size of int, it gets promoted no matter what its type is.
4028 // For instance, unsigned long bf : 4 gets promoted to signed int.
4029 if (BitWidth < IntSize)
4030 return IntTy;
4031
4032 if (BitWidth == IntSize)
4033 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4034
4035 // Types bigger than int are not subject to promotions, and therefore act
4036 // like the base type.
4037 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4038 // is ridiculous.
4039 return QualType();
4040}
4041
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004042/// getPromotedIntegerType - Returns the type that Promotable will
4043/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4044/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004045QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004046 assert(!Promotable.isNull());
4047 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004048 if (const EnumType *ET = Promotable->getAs<EnumType>())
4049 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004050
4051 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4052 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4053 // (3.9.1) can be converted to a prvalue of the first of the following
4054 // types that can represent all the values of its underlying type:
4055 // int, unsigned int, long int, unsigned long int, long long int, or
4056 // unsigned long long int [...]
4057 // FIXME: Is there some better way to compute this?
4058 if (BT->getKind() == BuiltinType::WChar_S ||
4059 BT->getKind() == BuiltinType::WChar_U ||
4060 BT->getKind() == BuiltinType::Char16 ||
4061 BT->getKind() == BuiltinType::Char32) {
4062 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4063 uint64_t FromSize = getTypeSize(BT);
4064 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4065 LongLongTy, UnsignedLongLongTy };
4066 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4067 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4068 if (FromSize < ToSize ||
4069 (FromSize == ToSize &&
4070 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4071 return PromoteTypes[Idx];
4072 }
4073 llvm_unreachable("char type should fit into long long");
4074 }
4075 }
4076
4077 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004078 if (Promotable->isSignedIntegerType())
4079 return IntTy;
4080 uint64_t PromotableSize = getTypeSize(Promotable);
4081 uint64_t IntSize = getTypeSize(IntTy);
4082 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4083 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4084}
4085
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004086/// \brief Recurses in pointer/array types until it finds an objc retainable
4087/// type and returns its ownership.
4088Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4089 while (!T.isNull()) {
4090 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4091 return T.getObjCLifetime();
4092 if (T->isArrayType())
4093 T = getBaseElementType(T);
4094 else if (const PointerType *PT = T->getAs<PointerType>())
4095 T = PT->getPointeeType();
4096 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004097 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004098 else
4099 break;
4100 }
4101
4102 return Qualifiers::OCL_None;
4103}
4104
Mike Stump11289f42009-09-09 15:08:12 +00004105/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004106/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004107/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004108int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004109 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4110 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004111 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004112
Chris Lattner76a00cf2008-04-06 22:59:24 +00004113 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4114 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004115
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004116 unsigned LHSRank = getIntegerRank(LHSC);
4117 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004118
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004119 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4120 if (LHSRank == RHSRank) return 0;
4121 return LHSRank > RHSRank ? 1 : -1;
4122 }
Mike Stump11289f42009-09-09 15:08:12 +00004123
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004124 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4125 if (LHSUnsigned) {
4126 // If the unsigned [LHS] type is larger, return it.
4127 if (LHSRank >= RHSRank)
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;
4134 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004135
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004136 // If the unsigned [RHS] type is larger, return it.
4137 if (RHSRank >= LHSRank)
4138 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004139
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004140 // If the signed type can represent all values of the unsigned type, it
4141 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004142 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004143 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004144}
Anders Carlsson98f07902007-08-17 05:31:46 +00004145
Anders Carlsson6d417272009-11-14 21:45:58 +00004146static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004147CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4148 DeclContext *DC, IdentifierInfo *Id) {
4149 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004150 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004151 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004152 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004153 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004154}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004155
Mike Stump11289f42009-09-09 15:08:12 +00004156// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004157QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004158 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004159 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004160 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004161 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004162 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004163
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004164 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004165
Anders Carlsson98f07902007-08-17 05:31:46 +00004166 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004167 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004168 // int flags;
4169 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004170 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004171 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004172 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004173 FieldTypes[3] = LongTy;
4174
Anders Carlsson98f07902007-08-17 05:31:46 +00004175 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004176 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004177 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004178 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004179 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004180 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004181 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004182 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004183 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004184 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004185 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004186 }
4187
Douglas Gregord5058122010-02-11 01:19:42 +00004188 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004189 }
Mike Stump11289f42009-09-09 15:08:12 +00004190
Anders Carlsson98f07902007-08-17 05:31:46 +00004191 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004192}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004193
Douglas Gregor512b0772009-04-23 22:29:11 +00004194void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004195 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004196 assert(Rec && "Invalid CFConstantStringType");
4197 CFConstantStringTypeDecl = Rec->getDecl();
4198}
4199
Jay Foad39c79802011-01-12 09:06:06 +00004200QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004201 if (BlockDescriptorType)
4202 return getTagDeclType(BlockDescriptorType);
4203
4204 RecordDecl *T;
4205 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004206 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004207 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004208 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004209
4210 QualType FieldTypes[] = {
4211 UnsignedLongTy,
4212 UnsignedLongTy,
4213 };
4214
4215 const char *FieldNames[] = {
4216 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004217 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004218 };
4219
4220 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004221 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004222 SourceLocation(),
4223 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004224 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004225 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004226 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004227 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004228 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004229 T->addDecl(Field);
4230 }
4231
Douglas Gregord5058122010-02-11 01:19:42 +00004232 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004233
4234 BlockDescriptorType = T;
4235
4236 return getTagDeclType(BlockDescriptorType);
4237}
4238
Jay Foad39c79802011-01-12 09:06:06 +00004239QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004240 if (BlockDescriptorExtendedType)
4241 return getTagDeclType(BlockDescriptorExtendedType);
4242
4243 RecordDecl *T;
4244 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004245 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004246 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004247 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004248
4249 QualType FieldTypes[] = {
4250 UnsignedLongTy,
4251 UnsignedLongTy,
4252 getPointerType(VoidPtrTy),
4253 getPointerType(VoidPtrTy)
4254 };
4255
4256 const char *FieldNames[] = {
4257 "reserved",
4258 "Size",
4259 "CopyFuncPtr",
4260 "DestroyFuncPtr"
4261 };
4262
4263 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004264 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004265 SourceLocation(),
4266 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004267 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004268 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004269 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004270 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004271 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004272 T->addDecl(Field);
4273 }
4274
Douglas Gregord5058122010-02-11 01:19:42 +00004275 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004276
4277 BlockDescriptorExtendedType = T;
4278
4279 return getTagDeclType(BlockDescriptorExtendedType);
4280}
4281
Jay Foad39c79802011-01-12 09:06:06 +00004282bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004283 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004284 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004285 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004286 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4287 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004288 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004289
4290 }
4291 }
Mike Stump94967902009-10-21 18:16:27 +00004292 return false;
4293}
4294
Jay Foad39c79802011-01-12 09:06:06 +00004295QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004296ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004297 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004298 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004299 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004300 // unsigned int __flags;
4301 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004302 // void *__copy_helper; // as needed
4303 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004304 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004305 // } *
4306
Mike Stump94967902009-10-21 18:16:27 +00004307 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4308
4309 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004310 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004311 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4312 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004313 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004314 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004315 T->startDefinition();
4316 QualType Int32Ty = IntTy;
4317 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4318 QualType FieldTypes[] = {
4319 getPointerType(VoidPtrTy),
4320 getPointerType(getTagDeclType(T)),
4321 Int32Ty,
4322 Int32Ty,
4323 getPointerType(VoidPtrTy),
4324 getPointerType(VoidPtrTy),
4325 Ty
4326 };
4327
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004328 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004329 "__isa",
4330 "__forwarding",
4331 "__flags",
4332 "__size",
4333 "__copy_helper",
4334 "__destroy_helper",
4335 DeclName,
4336 };
4337
4338 for (size_t i = 0; i < 7; ++i) {
4339 if (!HasCopyAndDispose && i >=4 && i <= 5)
4340 continue;
4341 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004342 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004343 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004344 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004345 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004346 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004347 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004348 T->addDecl(Field);
4349 }
4350
Douglas Gregord5058122010-02-11 01:19:42 +00004351 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004352
4353 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004354}
4355
Douglas Gregorbab8a962011-09-08 01:46:34 +00004356TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4357 if (!ObjCInstanceTypeDecl)
4358 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4359 getTranslationUnitDecl(),
4360 SourceLocation(),
4361 SourceLocation(),
4362 &Idents.get("instancetype"),
4363 getTrivialTypeSourceInfo(getObjCIdType()));
4364 return ObjCInstanceTypeDecl;
4365}
4366
Anders Carlsson18acd442007-10-29 06:33:42 +00004367// This returns true if a type has been typedefed to BOOL:
4368// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004369static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004370 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004371 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4372 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004373
Anders Carlssond8499822007-10-29 05:01:08 +00004374 return false;
4375}
4376
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004377/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004378/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004379CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004380 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4381 return CharUnits::Zero();
4382
Ken Dyck40775002010-01-11 17:06:35 +00004383 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004384
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004385 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004386 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004387 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004388 // Treat arrays as pointers, since that's how they're passed in.
4389 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004390 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004391 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004392}
4393
4394static inline
4395std::string charUnitsToString(const CharUnits &CU) {
4396 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004397}
4398
John McCall351762c2011-02-07 10:33:21 +00004399/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004400/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004401std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4402 std::string S;
4403
David Chisnall950a9512009-11-17 19:33:30 +00004404 const BlockDecl *Decl = Expr->getBlockDecl();
4405 QualType BlockTy =
4406 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4407 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004408 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004409 // Compute size of all parameters.
4410 // Start with computing size of a pointer in number of bytes.
4411 // FIXME: There might(should) be a better way of doing this computation!
4412 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004413 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4414 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004415 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004416 E = Decl->param_end(); PI != E; ++PI) {
4417 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004418 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004419 if (sz.isZero())
4420 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004421 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004422 ParmOffset += sz;
4423 }
4424 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004425 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004426 // Block pointer and offset.
4427 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004428
4429 // Argument types.
4430 ParmOffset = PtrSize;
4431 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4432 Decl->param_end(); PI != E; ++PI) {
4433 ParmVarDecl *PVDecl = *PI;
4434 QualType PType = PVDecl->getOriginalType();
4435 if (const ArrayType *AT =
4436 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4437 // Use array's original type only if it has known number of
4438 // elements.
4439 if (!isa<ConstantArrayType>(AT))
4440 PType = PVDecl->getType();
4441 } else if (PType->isFunctionType())
4442 PType = PVDecl->getType();
4443 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004444 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004445 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004446 }
John McCall351762c2011-02-07 10:33:21 +00004447
4448 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004449}
4450
Douglas Gregora9d84932011-05-27 01:19:52 +00004451bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004452 std::string& S) {
4453 // Encode result type.
4454 getObjCEncodingForType(Decl->getResultType(), S);
4455 CharUnits ParmOffset;
4456 // Compute size of all parameters.
4457 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4458 E = Decl->param_end(); PI != E; ++PI) {
4459 QualType PType = (*PI)->getType();
4460 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004461 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004462 continue;
4463
David Chisnall50e4eba2010-12-30 14:05:53 +00004464 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004465 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004466 ParmOffset += sz;
4467 }
4468 S += charUnitsToString(ParmOffset);
4469 ParmOffset = CharUnits::Zero();
4470
4471 // Argument types.
4472 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4473 E = Decl->param_end(); PI != E; ++PI) {
4474 ParmVarDecl *PVDecl = *PI;
4475 QualType PType = PVDecl->getOriginalType();
4476 if (const ArrayType *AT =
4477 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4478 // Use array's original type only if it has known number of
4479 // elements.
4480 if (!isa<ConstantArrayType>(AT))
4481 PType = PVDecl->getType();
4482 } else if (PType->isFunctionType())
4483 PType = PVDecl->getType();
4484 getObjCEncodingForType(PType, S);
4485 S += charUnitsToString(ParmOffset);
4486 ParmOffset += getObjCEncodingTypeSize(PType);
4487 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004488
4489 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004490}
4491
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004492/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4493/// method parameter or return type. If Extended, include class names and
4494/// block object types.
4495void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4496 QualType T, std::string& S,
4497 bool Extended) const {
4498 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4499 getObjCEncodingForTypeQualifier(QT, S);
4500 // Encode parameter type.
4501 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4502 true /*OutermostType*/,
4503 false /*EncodingProperty*/,
4504 false /*StructField*/,
4505 Extended /*EncodeBlockParameters*/,
4506 Extended /*EncodeClassNames*/);
4507}
4508
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004509/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004510/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004511bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004512 std::string& S,
4513 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004514 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004515 // Encode return type.
4516 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4517 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004518 // Compute size of all parameters.
4519 // Start with computing size of a pointer in number of bytes.
4520 // FIXME: There might(should) be a better way of doing this computation!
4521 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004522 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004523 // The first two arguments (self and _cmd) are pointers; account for
4524 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004525 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004526 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004527 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004528 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004529 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004530 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004531 continue;
4532
Ken Dyck40775002010-01-11 17:06:35 +00004533 assert (sz.isPositive() &&
4534 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004535 ParmOffset += sz;
4536 }
Ken Dyck40775002010-01-11 17:06:35 +00004537 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004538 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004539 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004540
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004541 // Argument types.
4542 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004543 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004544 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004545 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004546 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004547 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004548 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4549 // Use array's original type only if it has known number of
4550 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004551 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004552 PType = PVDecl->getType();
4553 } else if (PType->isFunctionType())
4554 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004555 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4556 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004557 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004558 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004559 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004560
4561 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004562}
4563
Daniel Dunbar4932b362008-08-28 04:38:10 +00004564/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004565/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004566/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4567/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004568/// Property attributes are stored as a comma-delimited C string. The simple
4569/// attributes readonly and bycopy are encoded as single characters. The
4570/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4571/// encoded as single characters, followed by an identifier. Property types
4572/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004573/// these attributes are defined by the following enumeration:
4574/// @code
4575/// enum PropertyAttributes {
4576/// kPropertyReadOnly = 'R', // property is read-only.
4577/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4578/// kPropertyByref = '&', // property is a reference to the value last assigned
4579/// kPropertyDynamic = 'D', // property is dynamic
4580/// kPropertyGetter = 'G', // followed by getter selector name
4581/// kPropertySetter = 'S', // followed by setter selector name
4582/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004583/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004584/// kPropertyWeak = 'W' // 'weak' property
4585/// kPropertyStrong = 'P' // property GC'able
4586/// kPropertyNonAtomic = 'N' // property non-atomic
4587/// };
4588/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004589void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004590 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004591 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004592 // Collect information from the property implementation decl(s).
4593 bool Dynamic = false;
4594 ObjCPropertyImplDecl *SynthesizePID = 0;
4595
4596 // FIXME: Duplicated code due to poor abstraction.
4597 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004598 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004599 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4600 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004601 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004602 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004603 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004604 if (PID->getPropertyDecl() == PD) {
4605 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4606 Dynamic = true;
4607 } else {
4608 SynthesizePID = PID;
4609 }
4610 }
4611 }
4612 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004613 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004614 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004615 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004616 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004617 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004618 if (PID->getPropertyDecl() == PD) {
4619 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4620 Dynamic = true;
4621 } else {
4622 SynthesizePID = PID;
4623 }
4624 }
Mike Stump11289f42009-09-09 15:08:12 +00004625 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004626 }
4627 }
4628
4629 // FIXME: This is not very efficient.
4630 S = "T";
4631
4632 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004633 // GCC has some special rules regarding encoding of properties which
4634 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004635 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004636 true /* outermost type */,
4637 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004638
4639 if (PD->isReadOnly()) {
4640 S += ",R";
4641 } else {
4642 switch (PD->getSetterKind()) {
4643 case ObjCPropertyDecl::Assign: break;
4644 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004645 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004646 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004647 }
4648 }
4649
4650 // It really isn't clear at all what this means, since properties
4651 // are "dynamic by default".
4652 if (Dynamic)
4653 S += ",D";
4654
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004655 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4656 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004657
Daniel Dunbar4932b362008-08-28 04:38:10 +00004658 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4659 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004660 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004661 }
4662
4663 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4664 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004665 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004666 }
4667
4668 if (SynthesizePID) {
4669 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4670 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004671 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004672 }
4673
4674 // FIXME: OBJCGC: weak & strong
4675}
4676
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004677/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004678/// Another legacy compatibility encoding: 32-bit longs are encoded as
4679/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004680/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4681///
4682void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004683 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004684 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004685 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004686 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004687 else
Jay Foad39c79802011-01-12 09:06:06 +00004688 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004689 PointeeTy = IntTy;
4690 }
4691 }
4692}
4693
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004694void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004695 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004696 // We follow the behavior of gcc, expanding structures which are
4697 // directly pointed to, and expanding embedded structures. Note that
4698 // these rules are sufficient to prevent recursive encoding of the
4699 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004700 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004701 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004702}
4703
David Chisnallb190a2c2010-06-04 01:10:52 +00004704static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4705 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004706 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004707 case BuiltinType::Void: return 'v';
4708 case BuiltinType::Bool: return 'B';
4709 case BuiltinType::Char_U:
4710 case BuiltinType::UChar: return 'C';
4711 case BuiltinType::UShort: return 'S';
4712 case BuiltinType::UInt: return 'I';
4713 case BuiltinType::ULong:
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::UInt128: return 'T';
4716 case BuiltinType::ULongLong: return 'Q';
4717 case BuiltinType::Char_S:
4718 case BuiltinType::SChar: return 'c';
4719 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004720 case BuiltinType::WChar_S:
4721 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004722 case BuiltinType::Int: return 'i';
4723 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004724 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004725 case BuiltinType::LongLong: return 'q';
4726 case BuiltinType::Int128: return 't';
4727 case BuiltinType::Float: return 'f';
4728 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004729 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004730 }
4731}
4732
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004733static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4734 EnumDecl *Enum = ET->getDecl();
4735
4736 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4737 if (!Enum->isFixed())
4738 return 'i';
4739
4740 // The encoding of a fixed enum type matches its fixed underlying type.
4741 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4742}
4743
Jay Foad39c79802011-01-12 09:06:06 +00004744static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004745 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004746 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004747 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004748 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4749 // The GNU runtime requires more information; bitfields are encoded as b,
4750 // then the offset (in bits) of the first element, then the type of the
4751 // bitfield, then the size in bits. For example, in this structure:
4752 //
4753 // struct
4754 // {
4755 // int integer;
4756 // int flags:2;
4757 // };
4758 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4759 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4760 // information is not especially sensible, but we're stuck with it for
4761 // compatibility with GCC, although providing it breaks anything that
4762 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004763 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004764 const RecordDecl *RD = FD->getParent();
4765 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004766 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004767 if (const EnumType *ET = T->getAs<EnumType>())
4768 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004769 else
Jay Foad39c79802011-01-12 09:06:06 +00004770 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004771 }
Richard Smithcaf33902011-10-10 18:28:20 +00004772 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004773}
4774
Daniel Dunbar07d07852009-10-18 21:17:35 +00004775// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004776void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4777 bool ExpandPointedToStructures,
4778 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004779 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004780 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004781 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004782 bool StructField,
4783 bool EncodeBlockParameters,
4784 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004785 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004786 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004787 return EncodeBitField(this, S, T, FD);
4788 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004789 return;
4790 }
Mike Stump11289f42009-09-09 15:08:12 +00004791
John McCall9dd450b2009-09-21 23:43:11 +00004792 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004793 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004794 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004795 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004796 return;
4797 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004798
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004799 // encoding for pointer or r3eference types.
4800 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004801 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004802 if (PT->isObjCSelType()) {
4803 S += ':';
4804 return;
4805 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004806 PointeeTy = PT->getPointeeType();
4807 }
4808 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4809 PointeeTy = RT->getPointeeType();
4810 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004811 bool isReadOnly = false;
4812 // For historical/compatibility reasons, the read-only qualifier of the
4813 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4814 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004815 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004816 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004817 if (OutermostType && T.isConstQualified()) {
4818 isReadOnly = true;
4819 S += 'r';
4820 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004821 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004822 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004823 while (P->getAs<PointerType>())
4824 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004825 if (P.isConstQualified()) {
4826 isReadOnly = true;
4827 S += 'r';
4828 }
4829 }
4830 if (isReadOnly) {
4831 // Another legacy compatibility encoding. Some ObjC qualifier and type
4832 // combinations need to be rearranged.
4833 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004834 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004835 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004836 }
Mike Stump11289f42009-09-09 15:08:12 +00004837
Anders Carlssond8499822007-10-29 05:01:08 +00004838 if (PointeeTy->isCharType()) {
4839 // char pointer types should be encoded as '*' unless it is a
4840 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004841 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004842 S += '*';
4843 return;
4844 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004845 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004846 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4847 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4848 S += '#';
4849 return;
4850 }
4851 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4852 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4853 S += '@';
4854 return;
4855 }
4856 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004857 }
Anders Carlssond8499822007-10-29 05:01:08 +00004858 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004859 getLegacyIntegralTypeEncoding(PointeeTy);
4860
Mike Stump11289f42009-09-09 15:08:12 +00004861 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004862 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004863 return;
4864 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004865
Chris Lattnere7cabb92009-07-13 00:10:46 +00004866 if (const ArrayType *AT =
4867 // Ignore type qualifiers etc.
4868 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004869 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004870 // Incomplete arrays are encoded as a pointer to the array element.
4871 S += '^';
4872
Mike Stump11289f42009-09-09 15:08:12 +00004873 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004874 false, ExpandStructures, FD);
4875 } else {
4876 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004877
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004878 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4879 if (getTypeSize(CAT->getElementType()) == 0)
4880 S += '0';
4881 else
4882 S += llvm::utostr(CAT->getSize().getZExtValue());
4883 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004884 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004885 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4886 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004887 S += '0';
4888 }
Mike Stump11289f42009-09-09 15:08:12 +00004889
4890 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004891 false, ExpandStructures, FD);
4892 S += ']';
4893 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004894 return;
4895 }
Mike Stump11289f42009-09-09 15:08:12 +00004896
John McCall9dd450b2009-09-21 23:43:11 +00004897 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004898 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004899 return;
4900 }
Mike Stump11289f42009-09-09 15:08:12 +00004901
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004902 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004903 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004904 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004905 // Anonymous structures print as '?'
4906 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4907 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004908 if (ClassTemplateSpecializationDecl *Spec
4909 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4910 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4911 std::string TemplateArgsStr
4912 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004913 TemplateArgs.data(),
4914 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004915 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004916
4917 S += TemplateArgsStr;
4918 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004919 } else {
4920 S += '?';
4921 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004922 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004923 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004924 if (!RDecl->isUnion()) {
4925 getObjCEncodingForStructureImpl(RDecl, S, FD);
4926 } else {
4927 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4928 FieldEnd = RDecl->field_end();
4929 Field != FieldEnd; ++Field) {
4930 if (FD) {
4931 S += '"';
4932 S += Field->getNameAsString();
4933 S += '"';
4934 }
Mike Stump11289f42009-09-09 15:08:12 +00004935
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004936 // Special case bit-fields.
4937 if (Field->isBitField()) {
4938 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004939 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004940 } else {
4941 QualType qt = Field->getType();
4942 getLegacyIntegralTypeEncoding(qt);
4943 getObjCEncodingForTypeImpl(qt, S, false, true,
4944 FD, /*OutermostType*/false,
4945 /*EncodingProperty*/false,
4946 /*StructField*/true);
4947 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004948 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004949 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004950 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004951 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004952 return;
4953 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004954
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004955 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004956 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004957 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004958 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004959 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004960 return;
4961 }
Mike Stump11289f42009-09-09 15:08:12 +00004962
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004963 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004964 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004965 if (EncodeBlockParameters) {
4966 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4967
4968 S += '<';
4969 // Block return type
4970 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4971 ExpandPointedToStructures, ExpandStructures,
4972 FD,
4973 false /* OutermostType */,
4974 EncodingProperty,
4975 false /* StructField */,
4976 EncodeBlockParameters,
4977 EncodeClassNames);
4978 // Block self
4979 S += "@?";
4980 // Block parameters
4981 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4982 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4983 E = FPT->arg_type_end(); I && (I != E); ++I) {
4984 getObjCEncodingForTypeImpl(*I, S,
4985 ExpandPointedToStructures,
4986 ExpandStructures,
4987 FD,
4988 false /* OutermostType */,
4989 EncodingProperty,
4990 false /* StructField */,
4991 EncodeBlockParameters,
4992 EncodeClassNames);
4993 }
4994 }
4995 S += '>';
4996 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004997 return;
4998 }
Mike Stump11289f42009-09-09 15:08:12 +00004999
John McCall8b07ec22010-05-15 11:32:37 +00005000 // Ignore protocol qualifiers when mangling at this level.
5001 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
5002 T = OT->getBaseType();
5003
John McCall8ccfcb52009-09-24 19:53:00 +00005004 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005005 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005006 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005007 S += '{';
5008 const IdentifierInfo *II = OI->getIdentifier();
5009 S += II->getName();
5010 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005011 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005012 DeepCollectObjCIvars(OI, true, Ivars);
5013 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005014 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005015 if (Field->isBitField())
5016 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005017 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005018 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005019 }
5020 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005021 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005022 }
Mike Stump11289f42009-09-09 15:08:12 +00005023
John McCall9dd450b2009-09-21 23:43:11 +00005024 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005025 if (OPT->isObjCIdType()) {
5026 S += '@';
5027 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005028 }
Mike Stump11289f42009-09-09 15:08:12 +00005029
Steve Narofff0c86112009-10-28 22:03:49 +00005030 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5031 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5032 // Since this is a binary compatibility issue, need to consult with runtime
5033 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005034 S += '#';
5035 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005036 }
Mike Stump11289f42009-09-09 15:08:12 +00005037
Chris Lattnere7cabb92009-07-13 00:10:46 +00005038 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005039 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005040 ExpandPointedToStructures,
5041 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005042 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005043 // Note that we do extended encoding of protocol qualifer list
5044 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005045 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005046 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5047 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005048 S += '<';
5049 S += (*I)->getNameAsString();
5050 S += '>';
5051 }
5052 S += '"';
5053 }
5054 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005055 }
Mike Stump11289f42009-09-09 15:08:12 +00005056
Chris Lattnere7cabb92009-07-13 00:10:46 +00005057 QualType PointeeTy = OPT->getPointeeType();
5058 if (!EncodingProperty &&
5059 isa<TypedefType>(PointeeTy.getTypePtr())) {
5060 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005061 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005062 // {...};
5063 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005064 getObjCEncodingForTypeImpl(PointeeTy, S,
5065 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005066 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005067 return;
5068 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005069
5070 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005071 if (OPT->getInterfaceDecl() &&
5072 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005073 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005074 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005075 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5076 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005077 S += '<';
5078 S += (*I)->getNameAsString();
5079 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005080 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005081 S += '"';
5082 }
5083 return;
5084 }
Mike Stump11289f42009-09-09 15:08:12 +00005085
John McCalla9e6e8d2010-05-17 23:56:34 +00005086 // gcc just blithely ignores member pointers.
5087 // TODO: maybe there should be a mangling for these
5088 if (T->getAs<MemberPointerType>())
5089 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005090
5091 if (T->isVectorType()) {
5092 // This matches gcc's encoding, even though technically it is
5093 // insufficient.
5094 // FIXME. We should do a better job than gcc.
5095 return;
5096 }
5097
David Blaikie83d382b2011-09-23 05:06:16 +00005098 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005099}
5100
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005101void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5102 std::string &S,
5103 const FieldDecl *FD,
5104 bool includeVBases) const {
5105 assert(RDecl && "Expected non-null RecordDecl");
5106 assert(!RDecl->isUnion() && "Should not be called for unions");
5107 if (!RDecl->getDefinition())
5108 return;
5109
5110 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5111 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5112 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5113
5114 if (CXXRec) {
5115 for (CXXRecordDecl::base_class_iterator
5116 BI = CXXRec->bases_begin(),
5117 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5118 if (!BI->isVirtual()) {
5119 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005120 if (base->isEmpty())
5121 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005122 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005123 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5124 std::make_pair(offs, base));
5125 }
5126 }
5127 }
5128
5129 unsigned i = 0;
5130 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5131 FieldEnd = RDecl->field_end();
5132 Field != FieldEnd; ++Field, ++i) {
5133 uint64_t offs = layout.getFieldOffset(i);
5134 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005135 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005136 }
5137
5138 if (CXXRec && includeVBases) {
5139 for (CXXRecordDecl::base_class_iterator
5140 BI = CXXRec->vbases_begin(),
5141 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5142 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005143 if (base->isEmpty())
5144 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005145 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005146 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5147 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5148 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005149 }
5150 }
5151
5152 CharUnits size;
5153 if (CXXRec) {
5154 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5155 } else {
5156 size = layout.getSize();
5157 }
5158
5159 uint64_t CurOffs = 0;
5160 std::multimap<uint64_t, NamedDecl *>::iterator
5161 CurLayObj = FieldOrBaseOffsets.begin();
5162
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005163 if (CXXRec && CXXRec->isDynamicClass() &&
5164 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005165 if (FD) {
5166 S += "\"_vptr$";
5167 std::string recname = CXXRec->getNameAsString();
5168 if (recname.empty()) recname = "?";
5169 S += recname;
5170 S += '"';
5171 }
5172 S += "^^?";
5173 CurOffs += getTypeSize(VoidPtrTy);
5174 }
5175
5176 if (!RDecl->hasFlexibleArrayMember()) {
5177 // Mark the end of the structure.
5178 uint64_t offs = toBits(size);
5179 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5180 std::make_pair(offs, (NamedDecl*)0));
5181 }
5182
5183 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5184 assert(CurOffs <= CurLayObj->first);
5185
5186 if (CurOffs < CurLayObj->first) {
5187 uint64_t padding = CurLayObj->first - CurOffs;
5188 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5189 // packing/alignment of members is different that normal, in which case
5190 // the encoding will be out-of-sync with the real layout.
5191 // If the runtime switches to just consider the size of types without
5192 // taking into account alignment, we could make padding explicit in the
5193 // encoding (e.g. using arrays of chars). The encoding strings would be
5194 // longer then though.
5195 CurOffs += padding;
5196 }
5197
5198 NamedDecl *dcl = CurLayObj->second;
5199 if (dcl == 0)
5200 break; // reached end of structure.
5201
5202 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5203 // We expand the bases without their virtual bases since those are going
5204 // in the initial structure. Note that this differs from gcc which
5205 // expands virtual bases each time one is encountered in the hierarchy,
5206 // making the encoding type bigger than it really is.
5207 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005208 assert(!base->isEmpty());
5209 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005210 } else {
5211 FieldDecl *field = cast<FieldDecl>(dcl);
5212 if (FD) {
5213 S += '"';
5214 S += field->getNameAsString();
5215 S += '"';
5216 }
5217
5218 if (field->isBitField()) {
5219 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005220 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005221 } else {
5222 QualType qt = field->getType();
5223 getLegacyIntegralTypeEncoding(qt);
5224 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5225 /*OutermostType*/false,
5226 /*EncodingProperty*/false,
5227 /*StructField*/true);
5228 CurOffs += getTypeSize(field->getType());
5229 }
5230 }
5231 }
5232}
5233
Mike Stump11289f42009-09-09 15:08:12 +00005234void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005235 std::string& S) const {
5236 if (QT & Decl::OBJC_TQ_In)
5237 S += 'n';
5238 if (QT & Decl::OBJC_TQ_Inout)
5239 S += 'N';
5240 if (QT & Decl::OBJC_TQ_Out)
5241 S += 'o';
5242 if (QT & Decl::OBJC_TQ_Bycopy)
5243 S += 'O';
5244 if (QT & Decl::OBJC_TQ_Byref)
5245 S += 'R';
5246 if (QT & Decl::OBJC_TQ_Oneway)
5247 S += 'V';
5248}
5249
Douglas Gregor3ea72692011-08-12 05:46:01 +00005250TypedefDecl *ASTContext::getObjCIdDecl() const {
5251 if (!ObjCIdDecl) {
5252 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5253 T = getObjCObjectPointerType(T);
5254 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5255 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5256 getTranslationUnitDecl(),
5257 SourceLocation(), SourceLocation(),
5258 &Idents.get("id"), IdInfo);
5259 }
5260
5261 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005262}
5263
Douglas Gregor52e02802011-08-12 06:17:30 +00005264TypedefDecl *ASTContext::getObjCSelDecl() const {
5265 if (!ObjCSelDecl) {
5266 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5267 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5268 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5269 getTranslationUnitDecl(),
5270 SourceLocation(), SourceLocation(),
5271 &Idents.get("SEL"), SelInfo);
5272 }
5273 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005274}
5275
Douglas Gregor0a586182011-08-12 05:59:41 +00005276TypedefDecl *ASTContext::getObjCClassDecl() const {
5277 if (!ObjCClassDecl) {
5278 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5279 T = getObjCObjectPointerType(T);
5280 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5281 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5282 getTranslationUnitDecl(),
5283 SourceLocation(), SourceLocation(),
5284 &Idents.get("Class"), ClassInfo);
5285 }
5286
5287 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005288}
5289
Douglas Gregord53ae832012-01-17 18:09:05 +00005290ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5291 if (!ObjCProtocolClassDecl) {
5292 ObjCProtocolClassDecl
5293 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5294 SourceLocation(),
5295 &Idents.get("Protocol"),
5296 /*PrevDecl=*/0,
5297 SourceLocation(), true);
5298 }
5299
5300 return ObjCProtocolClassDecl;
5301}
5302
Meador Inge5d3fb222012-06-16 03:34:49 +00005303//===----------------------------------------------------------------------===//
5304// __builtin_va_list Construction Functions
5305//===----------------------------------------------------------------------===//
5306
5307static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5308 // typedef char* __builtin_va_list;
5309 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5310 TypeSourceInfo *TInfo
5311 = Context->getTrivialTypeSourceInfo(CharPtrType);
5312
5313 TypedefDecl *VaListTypeDecl
5314 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5315 Context->getTranslationUnitDecl(),
5316 SourceLocation(), SourceLocation(),
5317 &Context->Idents.get("__builtin_va_list"),
5318 TInfo);
5319 return VaListTypeDecl;
5320}
5321
5322static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5323 // typedef void* __builtin_va_list;
5324 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5325 TypeSourceInfo *TInfo
5326 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5327
5328 TypedefDecl *VaListTypeDecl
5329 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5330 Context->getTranslationUnitDecl(),
5331 SourceLocation(), SourceLocation(),
5332 &Context->Idents.get("__builtin_va_list"),
5333 TInfo);
5334 return VaListTypeDecl;
5335}
5336
5337static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5338 // typedef struct __va_list_tag {
5339 RecordDecl *VaListTagDecl;
5340
5341 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5342 Context->getTranslationUnitDecl(),
5343 &Context->Idents.get("__va_list_tag"));
5344 VaListTagDecl->startDefinition();
5345
5346 const size_t NumFields = 5;
5347 QualType FieldTypes[NumFields];
5348 const char *FieldNames[NumFields];
5349
5350 // unsigned char gpr;
5351 FieldTypes[0] = Context->UnsignedCharTy;
5352 FieldNames[0] = "gpr";
5353
5354 // unsigned char fpr;
5355 FieldTypes[1] = Context->UnsignedCharTy;
5356 FieldNames[1] = "fpr";
5357
5358 // unsigned short reserved;
5359 FieldTypes[2] = Context->UnsignedShortTy;
5360 FieldNames[2] = "reserved";
5361
5362 // void* overflow_arg_area;
5363 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5364 FieldNames[3] = "overflow_arg_area";
5365
5366 // void* reg_save_area;
5367 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5368 FieldNames[4] = "reg_save_area";
5369
5370 // Create fields
5371 for (unsigned i = 0; i < NumFields; ++i) {
5372 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5373 SourceLocation(),
5374 SourceLocation(),
5375 &Context->Idents.get(FieldNames[i]),
5376 FieldTypes[i], /*TInfo=*/0,
5377 /*BitWidth=*/0,
5378 /*Mutable=*/false,
5379 ICIS_NoInit);
5380 Field->setAccess(AS_public);
5381 VaListTagDecl->addDecl(Field);
5382 }
5383 VaListTagDecl->completeDefinition();
5384 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005385 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005386
5387 // } __va_list_tag;
5388 TypedefDecl *VaListTagTypedefDecl
5389 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5390 Context->getTranslationUnitDecl(),
5391 SourceLocation(), SourceLocation(),
5392 &Context->Idents.get("__va_list_tag"),
5393 Context->getTrivialTypeSourceInfo(VaListTagType));
5394 QualType VaListTagTypedefType =
5395 Context->getTypedefType(VaListTagTypedefDecl);
5396
5397 // typedef __va_list_tag __builtin_va_list[1];
5398 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5399 QualType VaListTagArrayType
5400 = Context->getConstantArrayType(VaListTagTypedefType,
5401 Size, ArrayType::Normal, 0);
5402 TypeSourceInfo *TInfo
5403 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5404 TypedefDecl *VaListTypedefDecl
5405 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5406 Context->getTranslationUnitDecl(),
5407 SourceLocation(), SourceLocation(),
5408 &Context->Idents.get("__builtin_va_list"),
5409 TInfo);
5410
5411 return VaListTypedefDecl;
5412}
5413
5414static TypedefDecl *
5415CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5416 // typedef struct __va_list_tag {
5417 RecordDecl *VaListTagDecl;
5418 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5419 Context->getTranslationUnitDecl(),
5420 &Context->Idents.get("__va_list_tag"));
5421 VaListTagDecl->startDefinition();
5422
5423 const size_t NumFields = 4;
5424 QualType FieldTypes[NumFields];
5425 const char *FieldNames[NumFields];
5426
5427 // unsigned gp_offset;
5428 FieldTypes[0] = Context->UnsignedIntTy;
5429 FieldNames[0] = "gp_offset";
5430
5431 // unsigned fp_offset;
5432 FieldTypes[1] = Context->UnsignedIntTy;
5433 FieldNames[1] = "fp_offset";
5434
5435 // void* overflow_arg_area;
5436 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5437 FieldNames[2] = "overflow_arg_area";
5438
5439 // void* reg_save_area;
5440 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5441 FieldNames[3] = "reg_save_area";
5442
5443 // Create fields
5444 for (unsigned i = 0; i < NumFields; ++i) {
5445 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5446 VaListTagDecl,
5447 SourceLocation(),
5448 SourceLocation(),
5449 &Context->Idents.get(FieldNames[i]),
5450 FieldTypes[i], /*TInfo=*/0,
5451 /*BitWidth=*/0,
5452 /*Mutable=*/false,
5453 ICIS_NoInit);
5454 Field->setAccess(AS_public);
5455 VaListTagDecl->addDecl(Field);
5456 }
5457 VaListTagDecl->completeDefinition();
5458 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005459 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005460
5461 // } __va_list_tag;
5462 TypedefDecl *VaListTagTypedefDecl
5463 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5464 Context->getTranslationUnitDecl(),
5465 SourceLocation(), SourceLocation(),
5466 &Context->Idents.get("__va_list_tag"),
5467 Context->getTrivialTypeSourceInfo(VaListTagType));
5468 QualType VaListTagTypedefType =
5469 Context->getTypedefType(VaListTagTypedefDecl);
5470
5471 // typedef __va_list_tag __builtin_va_list[1];
5472 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5473 QualType VaListTagArrayType
5474 = Context->getConstantArrayType(VaListTagTypedefType,
5475 Size, ArrayType::Normal,0);
5476 TypeSourceInfo *TInfo
5477 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5478 TypedefDecl *VaListTypedefDecl
5479 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5480 Context->getTranslationUnitDecl(),
5481 SourceLocation(), SourceLocation(),
5482 &Context->Idents.get("__builtin_va_list"),
5483 TInfo);
5484
5485 return VaListTypedefDecl;
5486}
5487
5488static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5489 // typedef int __builtin_va_list[4];
5490 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5491 QualType IntArrayType
5492 = Context->getConstantArrayType(Context->IntTy,
5493 Size, ArrayType::Normal, 0);
5494 TypedefDecl *VaListTypedefDecl
5495 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5496 Context->getTranslationUnitDecl(),
5497 SourceLocation(), SourceLocation(),
5498 &Context->Idents.get("__builtin_va_list"),
5499 Context->getTrivialTypeSourceInfo(IntArrayType));
5500
5501 return VaListTypedefDecl;
5502}
5503
5504static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5505 TargetInfo::BuiltinVaListKind Kind) {
5506 switch (Kind) {
5507 case TargetInfo::CharPtrBuiltinVaList:
5508 return CreateCharPtrBuiltinVaListDecl(Context);
5509 case TargetInfo::VoidPtrBuiltinVaList:
5510 return CreateVoidPtrBuiltinVaListDecl(Context);
5511 case TargetInfo::PowerABIBuiltinVaList:
5512 return CreatePowerABIBuiltinVaListDecl(Context);
5513 case TargetInfo::X86_64ABIBuiltinVaList:
5514 return CreateX86_64ABIBuiltinVaListDecl(Context);
5515 case TargetInfo::PNaClABIBuiltinVaList:
5516 return CreatePNaClABIBuiltinVaListDecl(Context);
5517 }
5518
5519 llvm_unreachable("Unhandled __builtin_va_list type kind");
5520}
5521
5522TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5523 if (!BuiltinVaListDecl)
5524 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5525
5526 return BuiltinVaListDecl;
5527}
5528
Meador Ingecfb60902012-07-01 15:57:25 +00005529QualType ASTContext::getVaListTagType() const {
5530 // Force the creation of VaListTagTy by building the __builtin_va_list
5531 // declaration.
5532 if (VaListTagTy.isNull())
5533 (void) getBuiltinVaListDecl();
5534
5535 return VaListTagTy;
5536}
5537
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005538void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005539 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005540 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005541
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005542 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005543}
5544
John McCalld28ae272009-12-02 08:04:21 +00005545/// \brief Retrieve the template name that corresponds to a non-empty
5546/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005547TemplateName
5548ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5549 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005550 unsigned size = End - Begin;
5551 assert(size > 1 && "set is not overloaded!");
5552
5553 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5554 size * sizeof(FunctionTemplateDecl*));
5555 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5556
5557 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005558 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005559 NamedDecl *D = *I;
5560 assert(isa<FunctionTemplateDecl>(D) ||
5561 (isa<UsingShadowDecl>(D) &&
5562 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5563 *Storage++ = D;
5564 }
5565
5566 return TemplateName(OT);
5567}
5568
Douglas Gregordc572a32009-03-30 22:58:21 +00005569/// \brief Retrieve the template name that represents a qualified
5570/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005571TemplateName
5572ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5573 bool TemplateKeyword,
5574 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005575 assert(NNS && "Missing nested-name-specifier in qualified template name");
5576
Douglas Gregorc42075a2010-02-04 18:10:26 +00005577 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005578 llvm::FoldingSetNodeID ID;
5579 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5580
5581 void *InsertPos = 0;
5582 QualifiedTemplateName *QTN =
5583 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5584 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005585 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5586 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005587 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5588 }
5589
5590 return TemplateName(QTN);
5591}
5592
5593/// \brief Retrieve the template name that represents a dependent
5594/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005595TemplateName
5596ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5597 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005598 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005599 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005600
5601 llvm::FoldingSetNodeID ID;
5602 DependentTemplateName::Profile(ID, NNS, Name);
5603
5604 void *InsertPos = 0;
5605 DependentTemplateName *QTN =
5606 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5607
5608 if (QTN)
5609 return TemplateName(QTN);
5610
5611 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5612 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005613 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5614 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005615 } else {
5616 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005617 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5618 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005619 DependentTemplateName *CheckQTN =
5620 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5621 assert(!CheckQTN && "Dependent type name canonicalization broken");
5622 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005623 }
5624
5625 DependentTemplateNames.InsertNode(QTN, InsertPos);
5626 return TemplateName(QTN);
5627}
5628
Douglas Gregor71395fa2009-11-04 00:56:37 +00005629/// \brief Retrieve the template name that represents a dependent
5630/// template name such as \c MetaFun::template operator+.
5631TemplateName
5632ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005633 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005634 assert((!NNS || NNS->isDependent()) &&
5635 "Nested name specifier must be dependent");
5636
5637 llvm::FoldingSetNodeID ID;
5638 DependentTemplateName::Profile(ID, NNS, Operator);
5639
5640 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005641 DependentTemplateName *QTN
5642 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005643
5644 if (QTN)
5645 return TemplateName(QTN);
5646
5647 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5648 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005649 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5650 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005651 } else {
5652 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005653 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5654 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005655
5656 DependentTemplateName *CheckQTN
5657 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5658 assert(!CheckQTN && "Dependent template name canonicalization broken");
5659 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005660 }
5661
5662 DependentTemplateNames.InsertNode(QTN, InsertPos);
5663 return TemplateName(QTN);
5664}
5665
Douglas Gregor5590be02011-01-15 06:45:20 +00005666TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005667ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5668 TemplateName replacement) const {
5669 llvm::FoldingSetNodeID ID;
5670 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5671
5672 void *insertPos = 0;
5673 SubstTemplateTemplateParmStorage *subst
5674 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5675
5676 if (!subst) {
5677 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5678 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5679 }
5680
5681 return TemplateName(subst);
5682}
5683
5684TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005685ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5686 const TemplateArgument &ArgPack) const {
5687 ASTContext &Self = const_cast<ASTContext &>(*this);
5688 llvm::FoldingSetNodeID ID;
5689 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5690
5691 void *InsertPos = 0;
5692 SubstTemplateTemplateParmPackStorage *Subst
5693 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5694
5695 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005696 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005697 ArgPack.pack_size(),
5698 ArgPack.pack_begin());
5699 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5700 }
5701
5702 return TemplateName(Subst);
5703}
5704
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005705/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005706/// TargetInfo, produce the corresponding type. The unsigned @p Type
5707/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005708CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005709 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005710 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005711 case TargetInfo::SignedShort: return ShortTy;
5712 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5713 case TargetInfo::SignedInt: return IntTy;
5714 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5715 case TargetInfo::SignedLong: return LongTy;
5716 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5717 case TargetInfo::SignedLongLong: return LongLongTy;
5718 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5719 }
5720
David Blaikie83d382b2011-09-23 05:06:16 +00005721 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005722}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005723
5724//===----------------------------------------------------------------------===//
5725// Type Predicates.
5726//===----------------------------------------------------------------------===//
5727
Fariborz Jahanian96207692009-02-18 21:49:28 +00005728/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5729/// garbage collection attribute.
5730///
John McCall553d45a2011-01-12 00:34:59 +00005731Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005732 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005733 return Qualifiers::GCNone;
5734
David Blaikiebbafb8a2012-03-11 07:00:24 +00005735 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005736 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5737
5738 // Default behaviour under objective-C's gc is for ObjC pointers
5739 // (or pointers to them) be treated as though they were declared
5740 // as __strong.
5741 if (GCAttrs == Qualifiers::GCNone) {
5742 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5743 return Qualifiers::Strong;
5744 else if (Ty->isPointerType())
5745 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5746 } else {
5747 // It's not valid to set GC attributes on anything that isn't a
5748 // pointer.
5749#ifndef NDEBUG
5750 QualType CT = Ty->getCanonicalTypeInternal();
5751 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5752 CT = AT->getElementType();
5753 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5754#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005755 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005756 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005757}
5758
Chris Lattner49af6a42008-04-07 06:51:04 +00005759//===----------------------------------------------------------------------===//
5760// Type Compatibility Testing
5761//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005762
Mike Stump11289f42009-09-09 15:08:12 +00005763/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005764/// compatible.
5765static bool areCompatVectorTypes(const VectorType *LHS,
5766 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005767 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005768 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005769 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005770}
5771
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005772bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5773 QualType SecondVec) {
5774 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5775 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5776
5777 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5778 return true;
5779
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005780 // Treat Neon vector types and most AltiVec vector types as if they are the
5781 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005782 const VectorType *First = FirstVec->getAs<VectorType>();
5783 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005784 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005785 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005786 First->getVectorKind() != VectorType::AltiVecPixel &&
5787 First->getVectorKind() != VectorType::AltiVecBool &&
5788 Second->getVectorKind() != VectorType::AltiVecPixel &&
5789 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005790 return true;
5791
5792 return false;
5793}
5794
Steve Naroff8e6aee52009-07-23 01:01:38 +00005795//===----------------------------------------------------------------------===//
5796// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5797//===----------------------------------------------------------------------===//
5798
5799/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5800/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005801bool
5802ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5803 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005804 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005805 return true;
5806 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5807 E = rProto->protocol_end(); PI != E; ++PI)
5808 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5809 return true;
5810 return false;
5811}
5812
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005813/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00005814/// return true if lhs's protocols conform to rhs's protocol; false
5815/// otherwise.
5816bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5817 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5818 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5819 return false;
5820}
5821
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005822/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5823/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005824bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5825 QualType rhs) {
5826 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5827 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5828 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5829
5830 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5831 E = lhsQID->qual_end(); I != E; ++I) {
5832 bool match = false;
5833 ObjCProtocolDecl *lhsProto = *I;
5834 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5835 E = rhsOPT->qual_end(); J != E; ++J) {
5836 ObjCProtocolDecl *rhsProto = *J;
5837 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5838 match = true;
5839 break;
5840 }
5841 }
5842 if (!match)
5843 return false;
5844 }
5845 return true;
5846}
5847
Steve Naroff8e6aee52009-07-23 01:01:38 +00005848/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5849/// ObjCQualifiedIDType.
5850bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5851 bool compare) {
5852 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005853 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005854 lhs->isObjCIdType() || lhs->isObjCClassType())
5855 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005856 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005857 rhs->isObjCIdType() || rhs->isObjCClassType())
5858 return true;
5859
5860 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005861 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005862
Steve Naroff8e6aee52009-07-23 01:01:38 +00005863 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005864
Steve Naroff8e6aee52009-07-23 01:01:38 +00005865 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005866 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005867 // make sure we check the class hierarchy.
5868 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5869 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5870 E = lhsQID->qual_end(); I != E; ++I) {
5871 // when comparing an id<P> on lhs with a static type on rhs,
5872 // see if static class implements all of id's protocols, directly or
5873 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005874 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005875 return false;
5876 }
5877 }
5878 // If there are no qualifiers and no interface, we have an 'id'.
5879 return true;
5880 }
Mike Stump11289f42009-09-09 15:08:12 +00005881 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005882 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5883 E = lhsQID->qual_end(); I != E; ++I) {
5884 ObjCProtocolDecl *lhsProto = *I;
5885 bool match = false;
5886
5887 // when comparing an id<P> on lhs with a static type on rhs,
5888 // see if static class implements all of id's protocols, directly or
5889 // through its super class and categories.
5890 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5891 E = rhsOPT->qual_end(); J != E; ++J) {
5892 ObjCProtocolDecl *rhsProto = *J;
5893 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5894 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5895 match = true;
5896 break;
5897 }
5898 }
Mike Stump11289f42009-09-09 15:08:12 +00005899 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005900 // make sure we check the class hierarchy.
5901 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5902 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5903 E = lhsQID->qual_end(); I != E; ++I) {
5904 // when comparing an id<P> on lhs with a static type on rhs,
5905 // see if static class implements all of id's protocols, directly or
5906 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005907 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005908 match = true;
5909 break;
5910 }
5911 }
5912 }
5913 if (!match)
5914 return false;
5915 }
Mike Stump11289f42009-09-09 15:08:12 +00005916
Steve Naroff8e6aee52009-07-23 01:01:38 +00005917 return true;
5918 }
Mike Stump11289f42009-09-09 15:08:12 +00005919
Steve Naroff8e6aee52009-07-23 01:01:38 +00005920 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5921 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5922
Mike Stump11289f42009-09-09 15:08:12 +00005923 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005924 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005925 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005926 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5927 E = lhsOPT->qual_end(); I != E; ++I) {
5928 ObjCProtocolDecl *lhsProto = *I;
5929 bool match = false;
5930
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005931 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005932 // see if static class implements all of id's protocols, directly or
5933 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005934 // First, lhs protocols in the qualifier list must be found, direct
5935 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005936 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5937 E = rhsQID->qual_end(); J != E; ++J) {
5938 ObjCProtocolDecl *rhsProto = *J;
5939 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5940 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5941 match = true;
5942 break;
5943 }
5944 }
5945 if (!match)
5946 return false;
5947 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005948
5949 // Static class's protocols, or its super class or category protocols
5950 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5951 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5952 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5953 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5954 // This is rather dubious but matches gcc's behavior. If lhs has
5955 // no type qualifier and its class has no static protocol(s)
5956 // assume that it is mismatch.
5957 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5958 return false;
5959 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5960 LHSInheritedProtocols.begin(),
5961 E = LHSInheritedProtocols.end(); I != E; ++I) {
5962 bool match = false;
5963 ObjCProtocolDecl *lhsProto = (*I);
5964 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5965 E = rhsQID->qual_end(); J != E; ++J) {
5966 ObjCProtocolDecl *rhsProto = *J;
5967 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5968 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5969 match = true;
5970 break;
5971 }
5972 }
5973 if (!match)
5974 return false;
5975 }
5976 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005977 return true;
5978 }
5979 return false;
5980}
5981
Eli Friedman47f77112008-08-22 00:56:42 +00005982/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005983/// compatible for assignment from RHS to LHS. This handles validation of any
5984/// protocol qualifiers on the LHS or RHS.
5985///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005986bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5987 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005988 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5989 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5990
Steve Naroff1329fa02009-07-15 18:40:39 +00005991 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005992 if (LHS->isObjCUnqualifiedIdOrClass() ||
5993 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005994 return true;
5995
John McCall8b07ec22010-05-15 11:32:37 +00005996 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005997 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5998 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005999 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006000
6001 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6002 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6003 QualType(RHSOPT,0));
6004
John McCall8b07ec22010-05-15 11:32:37 +00006005 // If we have 2 user-defined types, fall into that path.
6006 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006007 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006008
Steve Naroff8e6aee52009-07-23 01:01:38 +00006009 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006010}
6011
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006012/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006013/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006014/// arguments in block literals. When passed as arguments, passing 'A*' where
6015/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6016/// not OK. For the return type, the opposite is not OK.
6017bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6018 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006019 const ObjCObjectPointerType *RHSOPT,
6020 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006021 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006022 return true;
6023
6024 if (LHSOPT->isObjCBuiltinType()) {
6025 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6026 }
6027
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006028 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006029 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6030 QualType(RHSOPT,0),
6031 false);
6032
6033 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6034 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6035 if (LHS && RHS) { // We have 2 user-defined types.
6036 if (LHS != RHS) {
6037 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006038 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006039 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006040 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006041 }
6042 else
6043 return true;
6044 }
6045 return false;
6046}
6047
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006048/// getIntersectionOfProtocols - This routine finds the intersection of set
6049/// of protocols inherited from two distinct objective-c pointer objects.
6050/// It is used to build composite qualifier list of the composite type of
6051/// the conditional expression involving two objective-c pointer objects.
6052static
6053void getIntersectionOfProtocols(ASTContext &Context,
6054 const ObjCObjectPointerType *LHSOPT,
6055 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006056 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006057
John McCall8b07ec22010-05-15 11:32:37 +00006058 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6059 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6060 assert(LHS->getInterface() && "LHS must have an interface base");
6061 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006062
6063 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6064 unsigned LHSNumProtocols = LHS->getNumProtocols();
6065 if (LHSNumProtocols > 0)
6066 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6067 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006068 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006069 Context.CollectInheritedProtocols(LHS->getInterface(),
6070 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006071 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6072 LHSInheritedProtocols.end());
6073 }
6074
6075 unsigned RHSNumProtocols = RHS->getNumProtocols();
6076 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006077 ObjCProtocolDecl **RHSProtocols =
6078 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006079 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6080 if (InheritedProtocolSet.count(RHSProtocols[i]))
6081 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006082 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006083 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006084 Context.CollectInheritedProtocols(RHS->getInterface(),
6085 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006086 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6087 RHSInheritedProtocols.begin(),
6088 E = RHSInheritedProtocols.end(); I != E; ++I)
6089 if (InheritedProtocolSet.count((*I)))
6090 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006091 }
6092}
6093
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006094/// areCommonBaseCompatible - Returns common base class of the two classes if
6095/// one found. Note that this is O'2 algorithm. But it will be called as the
6096/// last type comparison in a ?-exp of ObjC pointer types before a
6097/// warning is issued. So, its invokation is extremely rare.
6098QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006099 const ObjCObjectPointerType *Lptr,
6100 const ObjCObjectPointerType *Rptr) {
6101 const ObjCObjectType *LHS = Lptr->getObjectType();
6102 const ObjCObjectType *RHS = Rptr->getObjectType();
6103 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6104 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006105 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006106 return QualType();
6107
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006108 do {
John McCall8b07ec22010-05-15 11:32:37 +00006109 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006110 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006111 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006112 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6113
6114 QualType Result = QualType(LHS, 0);
6115 if (!Protocols.empty())
6116 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6117 Result = getObjCObjectPointerType(Result);
6118 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006119 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006120 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006121
6122 return QualType();
6123}
6124
John McCall8b07ec22010-05-15 11:32:37 +00006125bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6126 const ObjCObjectType *RHS) {
6127 assert(LHS->getInterface() && "LHS is not an interface type");
6128 assert(RHS->getInterface() && "RHS is not an interface type");
6129
Chris Lattner49af6a42008-04-07 06:51:04 +00006130 // Verify that the base decls are compatible: the RHS must be a subclass of
6131 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006132 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006133 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006134
Chris Lattner49af6a42008-04-07 06:51:04 +00006135 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6136 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006137 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006138 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006139
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006140 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6141 // more detailed analysis is required.
6142 if (RHS->getNumProtocols() == 0) {
6143 // OK, if LHS is a superclass of RHS *and*
6144 // this superclass is assignment compatible with LHS.
6145 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006146 bool IsSuperClass =
6147 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6148 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006149 // OK if conversion of LHS to SuperClass results in narrowing of types
6150 // ; i.e., SuperClass may implement at least one of the protocols
6151 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6152 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6153 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006154 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006155 // If super class has no protocols, it is not a match.
6156 if (SuperClassInheritedProtocols.empty())
6157 return false;
6158
6159 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6160 LHSPE = LHS->qual_end();
6161 LHSPI != LHSPE; LHSPI++) {
6162 bool SuperImplementsProtocol = false;
6163 ObjCProtocolDecl *LHSProto = (*LHSPI);
6164
6165 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6166 SuperClassInheritedProtocols.begin(),
6167 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6168 ObjCProtocolDecl *SuperClassProto = (*I);
6169 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6170 SuperImplementsProtocol = true;
6171 break;
6172 }
6173 }
6174 if (!SuperImplementsProtocol)
6175 return false;
6176 }
6177 return true;
6178 }
6179 return false;
6180 }
Mike Stump11289f42009-09-09 15:08:12 +00006181
John McCall8b07ec22010-05-15 11:32:37 +00006182 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6183 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006184 LHSPI != LHSPE; LHSPI++) {
6185 bool RHSImplementsProtocol = false;
6186
6187 // If the RHS doesn't implement the protocol on the left, the types
6188 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006189 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6190 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006191 RHSPI != RHSPE; RHSPI++) {
6192 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006193 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006194 break;
6195 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006196 }
6197 // FIXME: For better diagnostics, consider passing back the protocol name.
6198 if (!RHSImplementsProtocol)
6199 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006200 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006201 // The RHS implements all protocols listed on the LHS.
6202 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006203}
6204
Steve Naroffb7605152009-02-12 17:52:19 +00006205bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6206 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006207 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6208 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006209
Steve Naroff7cae42b2009-07-10 23:34:53 +00006210 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006211 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006212
6213 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6214 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006215}
6216
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006217bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6218 return canAssignObjCInterfaces(
6219 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6220 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6221}
6222
Mike Stump11289f42009-09-09 15:08:12 +00006223/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006224/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006225/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006226/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006227bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6228 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006229 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006230 return hasSameType(LHS, RHS);
6231
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006232 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006233}
6234
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006235bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006236 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006237}
6238
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006239bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6240 return !mergeTypes(LHS, RHS, true).isNull();
6241}
6242
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006243/// mergeTransparentUnionType - if T is a transparent union type and a member
6244/// of T is compatible with SubType, return the merged type, else return
6245/// QualType()
6246QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6247 bool OfBlockPointer,
6248 bool Unqualified) {
6249 if (const RecordType *UT = T->getAsUnionType()) {
6250 RecordDecl *UD = UT->getDecl();
6251 if (UD->hasAttr<TransparentUnionAttr>()) {
6252 for (RecordDecl::field_iterator it = UD->field_begin(),
6253 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006254 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006255 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6256 if (!MT.isNull())
6257 return MT;
6258 }
6259 }
6260 }
6261
6262 return QualType();
6263}
6264
6265/// mergeFunctionArgumentTypes - merge two types which appear as function
6266/// argument types
6267QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6268 bool OfBlockPointer,
6269 bool Unqualified) {
6270 // GNU extension: two types are compatible if they appear as a function
6271 // argument, one of the types is a transparent union type and the other
6272 // type is compatible with a union member
6273 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6274 Unqualified);
6275 if (!lmerge.isNull())
6276 return lmerge;
6277
6278 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6279 Unqualified);
6280 if (!rmerge.isNull())
6281 return rmerge;
6282
6283 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6284}
6285
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006286QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006287 bool OfBlockPointer,
6288 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006289 const FunctionType *lbase = lhs->getAs<FunctionType>();
6290 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006291 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6292 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006293 bool allLTypes = true;
6294 bool allRTypes = true;
6295
6296 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006297 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006298 if (OfBlockPointer) {
6299 QualType RHS = rbase->getResultType();
6300 QualType LHS = lbase->getResultType();
6301 bool UnqualifiedResult = Unqualified;
6302 if (!UnqualifiedResult)
6303 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006304 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006305 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006306 else
John McCall8c6b56f2010-12-15 01:06:38 +00006307 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6308 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006309 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006310
6311 if (Unqualified)
6312 retType = retType.getUnqualifiedType();
6313
6314 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6315 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6316 if (Unqualified) {
6317 LRetType = LRetType.getUnqualifiedType();
6318 RRetType = RRetType.getUnqualifiedType();
6319 }
6320
6321 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006322 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006323 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006324 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006325
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006326 // FIXME: double check this
6327 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6328 // rbase->getRegParmAttr() != 0 &&
6329 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006330 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6331 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006332
Douglas Gregor8c940862010-01-18 17:14:39 +00006333 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006334 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006335 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006336
John McCall8c6b56f2010-12-15 01:06:38 +00006337 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006338 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6339 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006340 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6341 return QualType();
6342
John McCall31168b02011-06-15 23:02:42 +00006343 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6344 return QualType();
6345
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006346 // functypes which return are preferred over those that do not.
6347 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6348 allLTypes = false;
6349 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6350 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006351 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6352 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006353
John McCall31168b02011-06-15 23:02:42 +00006354 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006355
Eli Friedman47f77112008-08-22 00:56:42 +00006356 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006357 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6358 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006359 unsigned lproto_nargs = lproto->getNumArgs();
6360 unsigned rproto_nargs = rproto->getNumArgs();
6361
6362 // Compatible functions must have the same number of arguments
6363 if (lproto_nargs != rproto_nargs)
6364 return QualType();
6365
6366 // Variadic and non-variadic functions aren't compatible
6367 if (lproto->isVariadic() != rproto->isVariadic())
6368 return QualType();
6369
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006370 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6371 return QualType();
6372
Fariborz Jahanian97676972011-09-28 21:52:05 +00006373 if (LangOpts.ObjCAutoRefCount &&
6374 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6375 return QualType();
6376
Eli Friedman47f77112008-08-22 00:56:42 +00006377 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006378 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006379 for (unsigned i = 0; i < lproto_nargs; i++) {
6380 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6381 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006382 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6383 OfBlockPointer,
6384 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006385 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006386
6387 if (Unqualified)
6388 argtype = argtype.getUnqualifiedType();
6389
Eli Friedman47f77112008-08-22 00:56:42 +00006390 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006391 if (Unqualified) {
6392 largtype = largtype.getUnqualifiedType();
6393 rargtype = rargtype.getUnqualifiedType();
6394 }
6395
Chris Lattner465fa322008-10-05 17:34:18 +00006396 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6397 allLTypes = false;
6398 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6399 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006400 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006401
Eli Friedman47f77112008-08-22 00:56:42 +00006402 if (allLTypes) return lhs;
6403 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006404
6405 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6406 EPI.ExtInfo = einfo;
6407 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006408 }
6409
6410 if (lproto) allRTypes = false;
6411 if (rproto) allLTypes = false;
6412
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006413 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006414 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006415 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006416 if (proto->isVariadic()) return QualType();
6417 // Check that the types are compatible with the types that
6418 // would result from default argument promotions (C99 6.7.5.3p15).
6419 // The only types actually affected are promotable integer
6420 // types and floats, which would be passed as a different
6421 // type depending on whether the prototype is visible.
6422 unsigned proto_nargs = proto->getNumArgs();
6423 for (unsigned i = 0; i < proto_nargs; ++i) {
6424 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006425
Eli Friedman448ce402012-08-30 00:44:15 +00006426 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006427 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006428 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6429 argTy = Enum->getDecl()->getIntegerType();
6430 if (argTy.isNull())
6431 return QualType();
6432 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006433
Eli Friedman47f77112008-08-22 00:56:42 +00006434 if (argTy->isPromotableIntegerType() ||
6435 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6436 return QualType();
6437 }
6438
6439 if (allLTypes) return lhs;
6440 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006441
6442 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6443 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006444 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006445 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006446 }
6447
6448 if (allLTypes) return lhs;
6449 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006450 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006451}
6452
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006453QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006454 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006455 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006456 // C++ [expr]: If an expression initially has the type "reference to T", the
6457 // type is adjusted to "T" prior to any further analysis, the expression
6458 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006459 // expression is an lvalue unless the reference is an rvalue reference and
6460 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006461 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6462 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006463
6464 if (Unqualified) {
6465 LHS = LHS.getUnqualifiedType();
6466 RHS = RHS.getUnqualifiedType();
6467 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006468
Eli Friedman47f77112008-08-22 00:56:42 +00006469 QualType LHSCan = getCanonicalType(LHS),
6470 RHSCan = getCanonicalType(RHS);
6471
6472 // If two types are identical, they are compatible.
6473 if (LHSCan == RHSCan)
6474 return LHS;
6475
John McCall8ccfcb52009-09-24 19:53:00 +00006476 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006477 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6478 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006479 if (LQuals != RQuals) {
6480 // If any of these qualifiers are different, we have a type
6481 // mismatch.
6482 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006483 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6484 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006485 return QualType();
6486
6487 // Exactly one GC qualifier difference is allowed: __strong is
6488 // okay if the other type has no GC qualifier but is an Objective
6489 // C object pointer (i.e. implicitly strong by default). We fix
6490 // this by pretending that the unqualified type was actually
6491 // qualified __strong.
6492 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6493 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6494 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6495
6496 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6497 return QualType();
6498
6499 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6500 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6501 }
6502 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6503 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6504 }
Eli Friedman47f77112008-08-22 00:56:42 +00006505 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006506 }
6507
6508 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006509
Eli Friedmandcca6332009-06-01 01:22:52 +00006510 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6511 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006512
Chris Lattnerfd652912008-01-14 05:45:46 +00006513 // We want to consider the two function types to be the same for these
6514 // comparisons, just force one to the other.
6515 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6516 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006517
6518 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006519 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6520 LHSClass = Type::ConstantArray;
6521 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6522 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006523
John McCall8b07ec22010-05-15 11:32:37 +00006524 // ObjCInterfaces are just specialized ObjCObjects.
6525 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6526 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6527
Nate Begemance4d7fc2008-04-18 23:10:10 +00006528 // Canonicalize ExtVector -> Vector.
6529 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6530 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006531
Chris Lattner95554662008-04-07 05:43:21 +00006532 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006533 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006534 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006535 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006536 // Compatibility is based on the underlying type, not the promotion
6537 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006538 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006539 QualType TINT = ETy->getDecl()->getIntegerType();
6540 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006541 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006542 }
John McCall9dd450b2009-09-21 23:43:11 +00006543 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006544 QualType TINT = ETy->getDecl()->getIntegerType();
6545 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006546 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006547 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006548 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006549 if (OfBlockPointer && !BlockReturnType) {
6550 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6551 return LHS;
6552 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6553 return RHS;
6554 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006555
Eli Friedman47f77112008-08-22 00:56:42 +00006556 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006557 }
Eli Friedman47f77112008-08-22 00:56:42 +00006558
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006559 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006560 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006561#define TYPE(Class, Base)
6562#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006563#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006564#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6565#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6566#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006567 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006568
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006569 case Type::LValueReference:
6570 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006571 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006572 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006573
John McCall8b07ec22010-05-15 11:32:37 +00006574 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006575 case Type::IncompleteArray:
6576 case Type::VariableArray:
6577 case Type::FunctionProto:
6578 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006579 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006580
Chris Lattnerfd652912008-01-14 05:45:46 +00006581 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006582 {
6583 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006584 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6585 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006586 if (Unqualified) {
6587 LHSPointee = LHSPointee.getUnqualifiedType();
6588 RHSPointee = RHSPointee.getUnqualifiedType();
6589 }
6590 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6591 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006592 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006593 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006594 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006595 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006596 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006597 return getPointerType(ResultType);
6598 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006599 case Type::BlockPointer:
6600 {
6601 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006602 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6603 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006604 if (Unqualified) {
6605 LHSPointee = LHSPointee.getUnqualifiedType();
6606 RHSPointee = RHSPointee.getUnqualifiedType();
6607 }
6608 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6609 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006610 if (ResultType.isNull()) return QualType();
6611 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6612 return LHS;
6613 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6614 return RHS;
6615 return getBlockPointerType(ResultType);
6616 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006617 case Type::Atomic:
6618 {
6619 // Merge two pointer types, while trying to preserve typedef info
6620 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6621 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6622 if (Unqualified) {
6623 LHSValue = LHSValue.getUnqualifiedType();
6624 RHSValue = RHSValue.getUnqualifiedType();
6625 }
6626 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6627 Unqualified);
6628 if (ResultType.isNull()) return QualType();
6629 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6630 return LHS;
6631 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6632 return RHS;
6633 return getAtomicType(ResultType);
6634 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006635 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006636 {
6637 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6638 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6639 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6640 return QualType();
6641
6642 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6643 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006644 if (Unqualified) {
6645 LHSElem = LHSElem.getUnqualifiedType();
6646 RHSElem = RHSElem.getUnqualifiedType();
6647 }
6648
6649 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006650 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006651 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6652 return LHS;
6653 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6654 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006655 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6656 ArrayType::ArraySizeModifier(), 0);
6657 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6658 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006659 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6660 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006661 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6662 return LHS;
6663 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6664 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006665 if (LVAT) {
6666 // FIXME: This isn't correct! But tricky to implement because
6667 // the array's size has to be the size of LHS, but the type
6668 // has to be different.
6669 return LHS;
6670 }
6671 if (RVAT) {
6672 // FIXME: This isn't correct! But tricky to implement because
6673 // the array's size has to be the size of RHS, but the type
6674 // has to be different.
6675 return RHS;
6676 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006677 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6678 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006679 return getIncompleteArrayType(ResultType,
6680 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006681 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006682 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006683 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006684 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006685 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006686 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006687 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006688 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006689 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006690 case Type::Complex:
6691 // Distinct complex types are incompatible.
6692 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006693 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006694 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006695 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6696 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006697 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006698 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006699 case Type::ObjCObject: {
6700 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006701 // FIXME: This should be type compatibility, e.g. whether
6702 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006703 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6704 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6705 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006706 return LHS;
6707
Eli Friedman47f77112008-08-22 00:56:42 +00006708 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006709 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006710 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006711 if (OfBlockPointer) {
6712 if (canAssignObjCInterfacesInBlockPointer(
6713 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006714 RHS->getAs<ObjCObjectPointerType>(),
6715 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006716 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006717 return QualType();
6718 }
John McCall9dd450b2009-09-21 23:43:11 +00006719 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6720 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006721 return LHS;
6722
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006723 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006724 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006725 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006726
David Blaikie8a40f702012-01-17 06:56:22 +00006727 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006728}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006729
Fariborz Jahanian97676972011-09-28 21:52:05 +00006730bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6731 const FunctionProtoType *FromFunctionType,
6732 const FunctionProtoType *ToFunctionType) {
6733 if (FromFunctionType->hasAnyConsumedArgs() !=
6734 ToFunctionType->hasAnyConsumedArgs())
6735 return false;
6736 FunctionProtoType::ExtProtoInfo FromEPI =
6737 FromFunctionType->getExtProtoInfo();
6738 FunctionProtoType::ExtProtoInfo ToEPI =
6739 ToFunctionType->getExtProtoInfo();
6740 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6741 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6742 ArgIdx != NumArgs; ++ArgIdx) {
6743 if (FromEPI.ConsumedArguments[ArgIdx] !=
6744 ToEPI.ConsumedArguments[ArgIdx])
6745 return false;
6746 }
6747 return true;
6748}
6749
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006750/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6751/// 'RHS' attributes and returns the merged version; including for function
6752/// return types.
6753QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6754 QualType LHSCan = getCanonicalType(LHS),
6755 RHSCan = getCanonicalType(RHS);
6756 // If two types are identical, they are compatible.
6757 if (LHSCan == RHSCan)
6758 return LHS;
6759 if (RHSCan->isFunctionType()) {
6760 if (!LHSCan->isFunctionType())
6761 return QualType();
6762 QualType OldReturnType =
6763 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6764 QualType NewReturnType =
6765 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6766 QualType ResReturnType =
6767 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6768 if (ResReturnType.isNull())
6769 return QualType();
6770 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6771 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6772 // In either case, use OldReturnType to build the new function type.
6773 const FunctionType *F = LHS->getAs<FunctionType>();
6774 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006775 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6776 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006777 QualType ResultType
6778 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006779 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006780 return ResultType;
6781 }
6782 }
6783 return QualType();
6784 }
6785
6786 // If the qualifiers are different, the types can still be merged.
6787 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6788 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6789 if (LQuals != RQuals) {
6790 // If any of these qualifiers are different, we have a type mismatch.
6791 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6792 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6793 return QualType();
6794
6795 // Exactly one GC qualifier difference is allowed: __strong is
6796 // okay if the other type has no GC qualifier but is an Objective
6797 // C object pointer (i.e. implicitly strong by default). We fix
6798 // this by pretending that the unqualified type was actually
6799 // qualified __strong.
6800 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6801 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6802 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6803
6804 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6805 return QualType();
6806
6807 if (GC_L == Qualifiers::Strong)
6808 return LHS;
6809 if (GC_R == Qualifiers::Strong)
6810 return RHS;
6811 return QualType();
6812 }
6813
6814 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6815 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6816 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6817 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6818 if (ResQT == LHSBaseQT)
6819 return LHS;
6820 if (ResQT == RHSBaseQT)
6821 return RHS;
6822 }
6823 return QualType();
6824}
6825
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006826//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006827// Integer Predicates
6828//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006829
Jay Foad39c79802011-01-12 09:06:06 +00006830unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006831 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006832 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006833 if (T->isBooleanType())
6834 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006835 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006836 return (unsigned)getTypeSize(T);
6837}
6838
Abramo Bagnara13640492012-09-09 10:21:24 +00006839QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006840 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006841
6842 // Turn <4 x signed int> -> <4 x unsigned int>
6843 if (const VectorType *VTy = T->getAs<VectorType>())
6844 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006845 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006846
6847 // For enums, we return the unsigned version of the base type.
6848 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006849 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006850
6851 const BuiltinType *BTy = T->getAs<BuiltinType>();
6852 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006853 switch (BTy->getKind()) {
6854 case BuiltinType::Char_S:
6855 case BuiltinType::SChar:
6856 return UnsignedCharTy;
6857 case BuiltinType::Short:
6858 return UnsignedShortTy;
6859 case BuiltinType::Int:
6860 return UnsignedIntTy;
6861 case BuiltinType::Long:
6862 return UnsignedLongTy;
6863 case BuiltinType::LongLong:
6864 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006865 case BuiltinType::Int128:
6866 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006867 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006868 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006869 }
6870}
6871
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006872ASTMutationListener::~ASTMutationListener() { }
6873
Chris Lattnerecd79c62009-06-14 00:45:47 +00006874
6875//===----------------------------------------------------------------------===//
6876// Builtin Type Computation
6877//===----------------------------------------------------------------------===//
6878
6879/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006880/// pointer over the consumed characters. This returns the resultant type. If
6881/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6882/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6883/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006884///
6885/// RequiresICE is filled in on return to indicate whether the value is required
6886/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006887static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006888 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006889 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006890 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006891 // Modifiers.
6892 int HowLong = 0;
6893 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006894 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006895
Chris Lattnerdc226c22010-10-01 22:42:38 +00006896 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006897 bool Done = false;
6898 while (!Done) {
6899 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006900 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006901 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006902 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006903 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006904 case 'S':
6905 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6906 assert(!Signed && "Can't use 'S' modifier multiple times!");
6907 Signed = true;
6908 break;
6909 case 'U':
6910 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6911 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6912 Unsigned = true;
6913 break;
6914 case 'L':
6915 assert(HowLong <= 2 && "Can't have LLLL modifier");
6916 ++HowLong;
6917 break;
6918 }
6919 }
6920
6921 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006922
Chris Lattnerecd79c62009-06-14 00:45:47 +00006923 // Read the base type.
6924 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006925 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006926 case 'v':
6927 assert(HowLong == 0 && !Signed && !Unsigned &&
6928 "Bad modifiers used with 'v'!");
6929 Type = Context.VoidTy;
6930 break;
6931 case 'f':
6932 assert(HowLong == 0 && !Signed && !Unsigned &&
6933 "Bad modifiers used with 'f'!");
6934 Type = Context.FloatTy;
6935 break;
6936 case 'd':
6937 assert(HowLong < 2 && !Signed && !Unsigned &&
6938 "Bad modifiers used with 'd'!");
6939 if (HowLong)
6940 Type = Context.LongDoubleTy;
6941 else
6942 Type = Context.DoubleTy;
6943 break;
6944 case 's':
6945 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6946 if (Unsigned)
6947 Type = Context.UnsignedShortTy;
6948 else
6949 Type = Context.ShortTy;
6950 break;
6951 case 'i':
6952 if (HowLong == 3)
6953 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6954 else if (HowLong == 2)
6955 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6956 else if (HowLong == 1)
6957 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6958 else
6959 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6960 break;
6961 case 'c':
6962 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6963 if (Signed)
6964 Type = Context.SignedCharTy;
6965 else if (Unsigned)
6966 Type = Context.UnsignedCharTy;
6967 else
6968 Type = Context.CharTy;
6969 break;
6970 case 'b': // boolean
6971 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6972 Type = Context.BoolTy;
6973 break;
6974 case 'z': // size_t.
6975 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6976 Type = Context.getSizeType();
6977 break;
6978 case 'F':
6979 Type = Context.getCFConstantStringType();
6980 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006981 case 'G':
6982 Type = Context.getObjCIdType();
6983 break;
6984 case 'H':
6985 Type = Context.getObjCSelType();
6986 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006987 case 'a':
6988 Type = Context.getBuiltinVaListType();
6989 assert(!Type.isNull() && "builtin va list type not initialized!");
6990 break;
6991 case 'A':
6992 // This is a "reference" to a va_list; however, what exactly
6993 // this means depends on how va_list is defined. There are two
6994 // different kinds of va_list: ones passed by value, and ones
6995 // passed by reference. An example of a by-value va_list is
6996 // x86, where va_list is a char*. An example of by-ref va_list
6997 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6998 // we want this argument to be a char*&; for x86-64, we want
6999 // it to be a __va_list_tag*.
7000 Type = Context.getBuiltinVaListType();
7001 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007002 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007003 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007004 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007005 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007006 break;
7007 case 'V': {
7008 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007009 unsigned NumElements = strtoul(Str, &End, 10);
7010 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007011 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007012
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007013 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7014 RequiresICE, false);
7015 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007016
7017 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007018 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007019 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007020 break;
7021 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007022 case 'E': {
7023 char *End;
7024
7025 unsigned NumElements = strtoul(Str, &End, 10);
7026 assert(End != Str && "Missing vector size");
7027
7028 Str = End;
7029
7030 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7031 false);
7032 Type = Context.getExtVectorType(ElementType, NumElements);
7033 break;
7034 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007035 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007036 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7037 false);
7038 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007039 Type = Context.getComplexType(ElementType);
7040 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007041 }
7042 case 'Y' : {
7043 Type = Context.getPointerDiffType();
7044 break;
7045 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007046 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007047 Type = Context.getFILEType();
7048 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007049 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007050 return QualType();
7051 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007052 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007053 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007054 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007055 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007056 else
7057 Type = Context.getjmp_bufType();
7058
Mike Stump2adb4da2009-07-28 23:47:15 +00007059 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007060 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007061 return QualType();
7062 }
7063 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007064 case 'K':
7065 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7066 Type = Context.getucontext_tType();
7067
7068 if (Type.isNull()) {
7069 Error = ASTContext::GE_Missing_ucontext;
7070 return QualType();
7071 }
7072 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007073 }
Mike Stump11289f42009-09-09 15:08:12 +00007074
Chris Lattnerdc226c22010-10-01 22:42:38 +00007075 // If there are modifiers and if we're allowed to parse them, go for it.
7076 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007077 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007078 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007079 default: Done = true; --Str; break;
7080 case '*':
7081 case '&': {
7082 // Both pointers and references can have their pointee types
7083 // qualified with an address space.
7084 char *End;
7085 unsigned AddrSpace = strtoul(Str, &End, 10);
7086 if (End != Str && AddrSpace != 0) {
7087 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7088 Str = End;
7089 }
7090 if (c == '*')
7091 Type = Context.getPointerType(Type);
7092 else
7093 Type = Context.getLValueReferenceType(Type);
7094 break;
7095 }
7096 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7097 case 'C':
7098 Type = Type.withConst();
7099 break;
7100 case 'D':
7101 Type = Context.getVolatileType(Type);
7102 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007103 case 'R':
7104 Type = Type.withRestrict();
7105 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007106 }
7107 }
Chris Lattner84733392010-10-01 07:13:18 +00007108
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007109 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007110 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007111
Chris Lattnerecd79c62009-06-14 00:45:47 +00007112 return Type;
7113}
7114
7115/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007116QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007117 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007118 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007119 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007120
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007121 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007122
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007123 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007124 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007125 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7126 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007127 if (Error != GE_None)
7128 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007129
7130 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7131
Chris Lattnerecd79c62009-06-14 00:45:47 +00007132 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007133 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007134 if (Error != GE_None)
7135 return QualType();
7136
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007137 // If this argument is required to be an IntegerConstantExpression and the
7138 // caller cares, fill in the bitmask we return.
7139 if (RequiresICE && IntegerConstantArgs)
7140 *IntegerConstantArgs |= 1 << ArgTypes.size();
7141
Chris Lattnerecd79c62009-06-14 00:45:47 +00007142 // Do array -> pointer decay. The builtin should use the decayed type.
7143 if (Ty->isArrayType())
7144 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007145
Chris Lattnerecd79c62009-06-14 00:45:47 +00007146 ArgTypes.push_back(Ty);
7147 }
7148
7149 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7150 "'.' should only occur at end of builtin type list!");
7151
John McCall991eb4b2010-12-21 00:44:39 +00007152 FunctionType::ExtInfo EI;
7153 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7154
7155 bool Variadic = (TypeStr[0] == '.');
7156
7157 // We really shouldn't be making a no-proto type here, especially in C++.
7158 if (ArgTypes.empty() && Variadic)
7159 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007160
John McCalldb40c7f2010-12-14 08:05:40 +00007161 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007162 EPI.ExtInfo = EI;
7163 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007164
7165 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007166}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007167
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007168GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7169 GVALinkage External = GVA_StrongExternal;
7170
7171 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007172 switch (L) {
7173 case NoLinkage:
7174 case InternalLinkage:
7175 case UniqueExternalLinkage:
7176 return GVA_Internal;
7177
7178 case ExternalLinkage:
7179 switch (FD->getTemplateSpecializationKind()) {
7180 case TSK_Undeclared:
7181 case TSK_ExplicitSpecialization:
7182 External = GVA_StrongExternal;
7183 break;
7184
7185 case TSK_ExplicitInstantiationDefinition:
7186 return GVA_ExplicitTemplateInstantiation;
7187
7188 case TSK_ExplicitInstantiationDeclaration:
7189 case TSK_ImplicitInstantiation:
7190 External = GVA_TemplateInstantiation;
7191 break;
7192 }
7193 }
7194
7195 if (!FD->isInlined())
7196 return External;
7197
David Blaikiebbafb8a2012-03-11 07:00:24 +00007198 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007199 // GNU or C99 inline semantics. Determine whether this symbol should be
7200 // externally visible.
7201 if (FD->isInlineDefinitionExternallyVisible())
7202 return External;
7203
7204 // C99 inline semantics, where the symbol is not externally visible.
7205 return GVA_C99Inline;
7206 }
7207
7208 // C++0x [temp.explicit]p9:
7209 // [ Note: The intent is that an inline function that is the subject of
7210 // an explicit instantiation declaration will still be implicitly
7211 // instantiated when used so that the body can be considered for
7212 // inlining, but that no out-of-line copy of the inline function would be
7213 // generated in the translation unit. -- end note ]
7214 if (FD->getTemplateSpecializationKind()
7215 == TSK_ExplicitInstantiationDeclaration)
7216 return GVA_C99Inline;
7217
7218 return GVA_CXXInline;
7219}
7220
7221GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7222 // If this is a static data member, compute the kind of template
7223 // specialization. Otherwise, this variable is not part of a
7224 // template.
7225 TemplateSpecializationKind TSK = TSK_Undeclared;
7226 if (VD->isStaticDataMember())
7227 TSK = VD->getTemplateSpecializationKind();
7228
7229 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007230 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007231 VD->getType()->getLinkage() == UniqueExternalLinkage)
7232 L = UniqueExternalLinkage;
7233
7234 switch (L) {
7235 case NoLinkage:
7236 case InternalLinkage:
7237 case UniqueExternalLinkage:
7238 return GVA_Internal;
7239
7240 case ExternalLinkage:
7241 switch (TSK) {
7242 case TSK_Undeclared:
7243 case TSK_ExplicitSpecialization:
7244 return GVA_StrongExternal;
7245
7246 case TSK_ExplicitInstantiationDeclaration:
7247 llvm_unreachable("Variable should not be instantiated");
7248 // Fall through to treat this like any other instantiation.
7249
7250 case TSK_ExplicitInstantiationDefinition:
7251 return GVA_ExplicitTemplateInstantiation;
7252
7253 case TSK_ImplicitInstantiation:
7254 return GVA_TemplateInstantiation;
7255 }
7256 }
7257
David Blaikie8a40f702012-01-17 06:56:22 +00007258 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007259}
7260
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007261bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007262 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7263 if (!VD->isFileVarDecl())
7264 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007265 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007266 return false;
7267
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007268 // Weak references don't produce any output by themselves.
7269 if (D->hasAttr<WeakRefAttr>())
7270 return false;
7271
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007272 // Aliases and used decls are required.
7273 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7274 return true;
7275
7276 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7277 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007278 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007279 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007280
7281 // Constructors and destructors are required.
7282 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7283 return true;
7284
7285 // The key function for a class is required.
7286 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7287 const CXXRecordDecl *RD = MD->getParent();
7288 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7289 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7290 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7291 return true;
7292 }
7293 }
7294
7295 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7296
7297 // static, static inline, always_inline, and extern inline functions can
7298 // always be deferred. Normal inline functions can be deferred in C99/C++.
7299 // Implicit template instantiations can also be deferred in C++.
7300 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007301 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007302 return false;
7303 return true;
7304 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007305
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007306 const VarDecl *VD = cast<VarDecl>(D);
7307 assert(VD->isFileVarDecl() && "Expected file scoped var");
7308
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007309 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7310 return false;
7311
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007312 // Structs that have non-trivial constructors or destructors are required.
7313
7314 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007315 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007316 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7317 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007318 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7319 RD->hasTrivialCopyConstructor() &&
7320 RD->hasTrivialMoveConstructor() &&
7321 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007322 return true;
7323 }
7324 }
7325
7326 GVALinkage L = GetGVALinkageForVariable(VD);
7327 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7328 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7329 return false;
7330 }
7331
7332 return true;
7333}
Charles Davis53c59df2010-08-16 03:33:14 +00007334
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007335CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007336 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007337 return ABI->getDefaultMethodCallConv(isVariadic);
7338}
7339
7340CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7341 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7342 return CC_Default;
7343 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007344}
7345
Jay Foad39c79802011-01-12 09:06:06 +00007346bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007347 // Pass through to the C++ ABI object
7348 return ABI->isNearlyEmpty(RD);
7349}
7350
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007351MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007352 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007353 case CXXABI_ARM:
7354 case CXXABI_Itanium:
7355 return createItaniumMangleContext(*this, getDiagnostics());
7356 case CXXABI_Microsoft:
7357 return createMicrosoftMangleContext(*this, getDiagnostics());
7358 }
David Blaikie83d382b2011-09-23 05:06:16 +00007359 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007360}
7361
Charles Davis53c59df2010-08-16 03:33:14 +00007362CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007363
7364size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007365 return ASTRecordLayouts.getMemorySize()
7366 + llvm::capacity_in_bytes(ObjCLayouts)
7367 + llvm::capacity_in_bytes(KeyFunctions)
7368 + llvm::capacity_in_bytes(ObjCImpls)
7369 + llvm::capacity_in_bytes(BlockVarCopyInits)
7370 + llvm::capacity_in_bytes(DeclAttrs)
7371 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7372 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7373 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7374 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7375 + llvm::capacity_in_bytes(OverriddenMethods)
7376 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007377 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007378 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007379}
Ted Kremenek540017e2011-10-06 05:00:56 +00007380
Douglas Gregor63798542012-02-20 19:44:39 +00007381unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7382 CXXRecordDecl *Lambda = CallOperator->getParent();
7383 return LambdaMangleContexts[Lambda->getDeclContext()]
7384 .getManglingNumber(CallOperator);
7385}
7386
7387
Ted Kremenek540017e2011-10-06 05:00:56 +00007388void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7389 ParamIndices[D] = index;
7390}
7391
7392unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7393 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7394 assert(I != ParamIndices.end() &&
7395 "ParmIndices lacks entry set by ParmVarDecl");
7396 return I->second;
7397}